Reputation: 963
I have array of array like below.
[["a",0,0,0],["b",30,20,10],["c",40,50,60],["d",0,0,0],...]
I want to remove some array if sum of number inside of each array is zero and get following return.
[["b",30,20,10],["c",40,50,60],...]
Could anyone tell how I can implement logic to achieve this in JavaScript?
Upvotes: 1
Views: 441
Reputation: 157
This is the dumb method:
const array = [["a",0,0,0],["b",30,20,10],["c",40,50,60],["d",0,0,0]]
var filteredArray = []
for (const subArray of array) {
var subArrayJustNumbers = subArray.slice(0) // copy the subArray
subArrayJustNumbers.shift() // remove the the first object
var sum = 0 // add all the numbers in the subarray
for (const n of subArrayJustNumbers)
sum += n
if (sum != 0) { // if the sum of all numbers isn't zero, append it to the filteredArray
filteredArray.push(subArray)
}
}
Upvotes: 0
Reputation: 18423
Use filter
and reduce
to count sums of numbers:
const a = [
["a", 0, 0, 0],
["b", 30, 20, 10],
["c", 40, 50, 60],
["d", 0, 0, 0]
]
var filtered = a.filter(e => !!e.reduce((a, n) => isNaN(n) ? a : a+n, 0))
console.log(JSON.stringify(filtered))
Another approach:
const a = [
["a", 0, 0, 0],
["b", 30, 20, 10],
["c", 40, 50, 60],
["d", 0, 0, 0]
]
var f = []
while (e = a.pop())
if(e.reduce((a, n) => isNaN(n) ? a : a+n, 0)) f.push(e)
console.log(JSON.stringify(f))
Upvotes: 1
Reputation: 174
Lots of ways to do this. For me, it's easy to split the problem up into two parts.
Study up on the reduce and filter methods if you need to.
// Determine if a subarray adds up to 0.
function sumIsZero(arr) {
// You could also do
// const rest = arr.slice(1)
// If you're not familiar with rest spread operators
const [letter, ...rest] = arr;
return rest.reduce((x, y) => x + y, 0) === 0;
}
// Create a new array that only includes the subarrays that add up to 0
const filtered = arrs.filter(sumIsZero);
Upvotes: 1
Reputation: 50326
Use filter
method and return only those nestedarray where the sum is not 0
let x = [
["a", 0, 0, 0],
["b", 30, 20, 10],
["c", 40, 50, 60],
["d", 0, 0, 0]
];
let result = x.filter(function(item) {
// a variable to hold the sum
let sum = 0;
// since the first value of inner array is string
// start looping from index 1
for (var i = 1; i < item.length; i++) {
sum += item[i];
}
// return the nested array only if the sum is not 0
if (sum !== 0) {
return item;
}
})
console.log(result)
Upvotes: 1
Reputation: 371049
filter
the array of arrays, by iterating over each array and keeping track of the sum of the numbers in the array with reduce
:
const input = [
["a", 0, 0, 0],
["b", 30, 20, 10],
["c", 40, 50, 60],
["d", 0, 0, 0],
['e', 30, -30]
];
console.log(
input.filter((arr) => (
arr.reduce((a, item) => (
typeof item === 'number'
? a + item
: a
), 0)
))
);
Upvotes: 3