নেস্টেড অ্যারেকে ফ্ল্যাটেন করে একটি স্ট্রিংে রূপান্তর করা, প্রতিটি উপাদানের পরে স্পেস যোগ করে।
উদাহরণ
['this', ['is', 'an', ['example', 'of', ['nested', 'array']]]] → "this is an example of nested array "
রিকার্সিভ সমাধান
const arrayToString = (arr) => {
let str = '';
for (const item of arr) {
if (Array.isArray(item)) {
str += `${arrayToString(item)} `;
} else {
str += `${item} `;
}
}
return str;
};
// Reduce ব্যবহার করে
const arrayToStringReduce = (arr) => {
return arr.reduce((str, item) => {
return str + (Array.isArray(item) ? arrayToStringReduce(item) : item) + ' ';
}, '');
};
// Flat + Join (সেরা - ES2019)
const arrayToStringFlat = (arr) => {
return arr.flat(Infinity).join(' ') + ' ';
};
// টেস্ট
const arr = [
'this',
['is', 'an', ['example', 'of', ['nested', 'array']]]
];
console.log(arrayToString(arr)); // "this is an example of nested array "
console.log(arrayToStringReduce(arr)); // "this is an example of nested array "
console.log(arrayToStringFlat(arr)); // "this is an example of nested array "
Flat() মেথড ব্যাখ্যা
arr.flat(Infinity): যেকোনো গভীরতা পর্যন্ত ফ্ল্যাটেনarr.flat(2): ২ লেভেল পর্যন্ত ফ্ল্যাটেন- ব্রাউজার সাপোর্ট: Chrome 69+, Firefox 62+, Safari 12+
পারফরম্যান্স
flat(Infinity) নেটিভ ইমপ্লিমেন্টেশন হওয়ায় সবচেয়ে দ্রুত।
উৎপাদন
this is an example of nested array