简体   繁体   English

如何从 JS 中通过此函数运行的数组编号元素中删除“-”?

[英]How to remove '-' from the array number elements run through this function in JS?

I'm using this function below to sum "columns" of a 2D Array, but some elements contain '-' and I haven't been able to handle it:我在下面使用这个函数对二维数组的“列”求和,但有些元素包含'-' ,我无法处理它:

I've tried Number(num) or typeof num === 'number' , but still...我试过Number(num)typeof num === 'number' ,但仍然...

 const arr = [ ['-', 2, 21], [1, '-', 4, 54], [5, 2, 2], [11, 5, 3, 1] ]; const sumArray = (array) => { const newArray = []; array.forEach(sub => { sub.forEach((num, index) => { if(newArray[index]){ newArray[index] += num; }else{ newArray[index] = num; } }); }); return newArray; } console.log(sumArray(arr))

You could use map and reduce to achieve this as well.您也可以使用mapreduce来实现这一点。

const arr = [
  ['-', 2, 21],
  [1, '-', 4, 54],
  [5, 2, 2],
  [11, 5, 3, 1],
];

const sums = arr.map((sub) =>
  sub.reduce((previous, current) => {
    // check here that the value is a number
    if (typeof current === 'number') {
      return previous + current;
    }

    return previous;
  }, 0)
);

console.log(sums);

// returns [23, 59, 9, 20]

Try:尝试:

 const arr = [ ['-', 2, 21], [1, '-', 4, 54], [5, 2, 2], [11, 5, 3, 1] ]; const sumArray = (array) => { const newArray = []; array.forEach(sub => { sub.forEach((num, index) => { if (typeof num == 'number') { if (newArray[index]) { newArray[index] += num; } else { newArray[index] = num; } } }); }); return newArray; } console.log(sumArray(arr))

Here's a more concise solution:这是一个更简洁的解决方案:

 const arr = [ ['-', 2, 21], [1, '-', 4, 54], [5, 2, 2], [11, 5, 3, 1] ]; const result = arr.map((e, i) => arr.reduce((a, c) => (typeof c[i] == 'number'? a + c[i]: a), 0)) console.log(result)

Using splice() would help remove the - from the array使用 splice() 将有助于从数组中删除 -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM