How can I iterate over nested arrays with recursion? [duplicate] - javascript

This question already has answers here:
How can I check if an object is an array? [duplicate]
(51 answers)
Closed 3 years ago.
How can I iterate over nested arrays like this with recursion in javascript:
var a = [10, [1, [2,2,2], 3], 20, 'Hallo']
In Python it looks like this:
def foo1(L):
for i in L:
if not isinstance(i, list):
print(i)
else:
foo1(i)
foo1(a)
How can I write if not isinstance(i, list): in javascript?

You can use:
var a = [10, [1, [2,2,2], 3], 20, 'Hallo']
for (let item of a) {
if (!Array.isArray(item)){
console.log("Not array", item);
}else{
console.log("Array", item);
}
}

Related

How to transform array of arrays into one array [duplicate]

This question already has answers here:
All possible combinations of a 2d array in Javascript
(2 answers)
Closed 1 year ago.
I want to transform one array of arrays by doing a specific transform, like the following example:
[[1, 2, 3], [4, 5]] => [14, 15, 24, 25, 34, 35];
Note, the first element of the first array is concatenated to each element of the second array to form a new array, and so on with the second element, third... etc
Use array.concat and for loop
let arrays = [
["a1","b1","c1"],
["a2","b2","c2"],
["a1","b1","c1"],
["a1","b1","c1"],
]
let arr = [];
arrays.forEach(array =>{
arr = arr.concat(array)
})
console.log(arr)

Delete all the array items in JavaScript [duplicate]

This question already has answers here:
How do I empty an array in JavaScript?
(17 answers)
Closed 2 years ago.
How can I delete all the items from a JavaScript array?
example -
var myArray1, 2, 3, 4, 5, 6, 7, 8, 9];
// I want it to become this
myArray = [];
You can try this:
function clearArray(array) {
while (array.length) {
array.pop();
}
}

Why does this common JavaScript method to deeply flatten arrays not work universally? [duplicate]

This question already has answers here:
How to flatten nested array in javascript? [duplicate]
(27 answers)
Closed 2 years ago.
I run into this interesting code challenge: "Create a function that takes an array and returns the sum of all items in the array."
My solution is:
function sumArray(arr) {
var merged = [].concat.apply([], arr);
var sum = 0;
merged.forEach(function(item) {
sum = sum + item;
});
return sum;
}
The problem is that the above solution fails for: sumArray([1, [2, [1]], 3]), 7 because the flattening method does not go deep enough. Concretely, in the above case, console.log(merged) is [1, 2, [1], 3];
What flattening method would go as deep as necessary?
Use Array#flat() with infinite depth , or actual depth if known.
function sumArray(arr) {
return arr.flat(Infinity).reduce((a,b) => a+b)
}
console.log(sumArray([1, [2, [1]], 3]))

How to find an array in another array? [duplicate]

This question already has answers here:
How to check if an array contains another array?
(6 answers)
javascript search array of arrays
(12 answers)
How to compare arrays in JavaScript?
(55 answers)
Closed 3 years ago.
These codes don't work:
const a = [[1, 1], [2, 2]]
console.log(a.includes([1, 1])); // --> false
console.log(a.indexOf([1, 1])); // --> -1
This work but I think its not optimized
console.log(a.map(x => x.toString()).includes([1, 1].toString()));
// --> true
Is there a simpler way ?
const a = [[1, 1], [2, 2]]
var index=a.findIndex(x=>{return JSON.stringify(x)===JSON.stringify([2, 2])})
console.log(`item index : ${index}`);
Assuming this:
var arr = ['a', 'b', 'b'];
you can invoke:
Array.isArray(arr);
will return true if the considered variable is an array, otherwise not.
Once you get it, you can apply it to the external array.

Getting Sum for all first items in each array, all second items in each array etc. ES6 [duplicate]

This question already has answers here:
Summing ; delimited values in Javascript
(1 answer)
How to sum elements at the same index in array of arrays into a single array?
(7 answers)
Closed 5 years ago.
I am trying to add together an undetermined amount of arrays, but only add or reduce them item by item.
I cannot figure out how to make this work in ES6 javascript.
const arrayList = [
[1, 2, 3],
[1, 2, 3],
[2, 2, 2]
];
const totalRow = arrayList.map((array) => {
const total = [];
array.map((number, i) => {
total[i] = (total[i] == undefined ? 0 : total[i]) + number;
});
return total;
});
//Output is just 3 more arrays with no change, as it seems
//the total variable resets to an empty array with each iteration.
//what i want is this output:
[4, 6, 8]
What am I doing wrong? I tried reduce method as well but came up empty

Categories