Helpful array methods in javascript

Lets just say you have an array of arrays and you wanted to get them as a list, the imperative way would be to allocate a new array, then recursively iterate through the array. 

But the flat operator just does the same, it also provides us the ability to specify the nested level.

const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]
 
You can checkout the examples in mdn
 

When you want to find some element inside the array, i have seen most use the filter operator, but the right one would be find() operator

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
 

Share:

0 comments:

Post a Comment