[英]How to implement logic if sum of array is 0,remove from array in JavaScript?
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? 谁能说出我该如何在JavaScript中实现实现此目标的逻辑?
filter
the array of arrays, by iterating over each array and keeping track of the sum of the numbers in the array with reduce
: 通过遍历每个数组并使用reduce
跟踪数组中数字的总和来filter
数组的数组:
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) )) );
Use filter
method and return only those nestedarray where the sum is not 0 使用filter
方法并仅返回总和不为0的那些nestedarray
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)
Use filter
and reduce
to count sums of numbers: 使用filter
和reduce
来计算数字总和:
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))
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);
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.