I have an object like this
const obj = {
name: "abc",
arr: [{
key1: "value1",
arr1: [1, 2, 3]
}, {
key2: "value2",
arr2: [4, 5, 6]
}]
}
Here, i want to add the lengths of arrays arr1 and arr2, and return 6 as an answer. I know looping and calculating lenghts by for-in is one solution, but what can be a faster and more precise solution?
CodePudding user response:
It looks you want to count the lengths of arrays that only have primitive values as members, not of arrays which have (some) objects/arrays as members.
Here is a proposed recursive solution:
const isPrimitive = val => Object(val) !== val;
const isArrayOfPrimitive = arr => arr?.every?.(isPrimitive);
const deepLength = obj => isPrimitive(obj) ? 0
: Object.values(obj).reduce((sum, val) => sum deepLength(val),
isArrayOfPrimitive(obj) ? obj.length : 0);
// Example run:
const obj = {
name: "abc",
arr: [{
key1: "value1",
arr1: [1, 2, 3]
}, {
key2: "value2",
arr2: [4, 5, 6]
}]
};
console.log(deepLength(obj)); // 6
CodePudding user response:
const obj = {
name: "abc",
arr: [
{ key1: "value1", arr1: [1, 2, 3, 4, 6, 7, 9] },
{ key2: "value2", arr2: [4, 5, 6] }
]
}
function getNumbers(arr) {
let a = arr['arr'][0].arr1.length;
let b = arr['arr'][1].arr2.length;
let sum = a b;
return sum;
}
console.log(getNumbers(obj));