JavaScript Problem: Flattening an Array of Sub-arrays

preview_player
Показать описание
A multi-dimensional array is basically an array of sub-arrays. What if you had such an array and you needed to flatten it; take all of the elements and include them in a single array without any sub-arrays. That is the problem we will solve in this tutorial. The solutions involves recursion and uses other syntax in interesting ways.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

function flatten(arr) {
return [].concat(...arr)
}

minnuss
Автор

Can't remember where I learned about this trick, but we can use infinity in flat(). For example;

const myArray = [1, 2, [3, 4], 5, 6, [[7, 8], 9], 10, [[[11], 12], 13]];
let flatArray = myArray.flat(Infinity)
console.log(flatArray); //returns [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ]

karlstenator
Автор

Sir what happens when we are trying to compare two objects using new keyword. For example,
var str=new String("smith")
var str1 = new String ("smith")
If am trying to compare
C.l(str==str1)//false
C.l(str===str1)//false
Why am getting false here?
What is happening here when we are trying to compare two non-primitive datatype...please explain this sir...

tamilguru
Автор

const arrayDepth = (arr, currentDepth = 0, maxDepth = 0) => {
for (let e of arr) {
if (Array.isArray(e)) {
maxDepth = arrayDepth(e, currentDepth + 1, Math.max(currentDepth + 1, maxDepth));
}
}
return maxDepth;
}
const arr = [1, 2, 3, [10, 20, [100, 200], 30], [45], 7, [4, [7, [8, [9, [10, [15, [700,



OUTPUT:
7
[1, 2, 3, 10, 20, 100, 200, 30, 45, 7, 4, 7, 8, 9, 10, 15, 700, 80]

ErfanHossainShoaib