如果数组的总和为0,如何在JavaScript中从数组中删除逻辑呢?

时间:2018-07-29 01:41:26

标签: javascript arrays

我有如下数组。

[["a",0,0,0],["b",30,20,10],["c",40,50,60],["d",0,0,0],...]  

如果每个数组中数字的总和为零,我想删除一些数组,然后返回以下内容。

[["b",30,20,10],["c",40,50,60],...]  

谁能告诉我如何在JavaScript中实现逻辑来实现这一目标?

5 个答案:

答案 0 :(得分:3)

filter,通过遍历每个数组并使用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)
  ))
);

答案 1 :(得分:1)

使用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)

答案 2 :(得分:1)

使用filterreduce来计算数字总和:

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))

另一种方法:

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))

答案 3 :(得分:1)

很多方法可以做到这一点。对我来说,将问题分为两部分很容易。

  1. 找出数字是否等于0
  2. 删除总和为0的数组

根据需要研究reducefilter方法。

// 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);

答案 4 :(得分:0)

这是愚蠢的方法:

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)
    }
}