简体   繁体   English

从数组中删除所有特定值

[英]Remove all of a specific value from an array

i have an array called acceptedTermsPoints(), and it is outputting 0,3,3,0,0 which is fine.我有一个名为acceptedTermsPoints() 的数组,它输出0,3,3,0,0,这很好。 What i need is a way to remove all of the values equal to 0, so that the array is equal to 3, 3我需要的是一种删除所有等于 0 的值的方法,以便数组等于 3、3

I don't have any code but please use acceptedTermsPoints() in the example.我没有任何代码,但请在示例中使用acceptedTermsPoints()。 Thanks!谢谢! Any help is appreciated任何帮助表示赞赏

使用filter

var newArray = acceptedTermsPoints().filter(e => e != 0);

Try This尝试这个

var acceptedTermsPoints = [0,3,3,0,0];

function isGreaterThanZero(value) {
  return value > 0;
}
var NewacceptedTermsPoints = acceptedTermsPoints.filter(isGreaterThanZero);

Using filter with a functional approach:使用带有函数式方法的filter

function notEquals(n) {
  return function (el) {
    return el !== n;
  }
}

function removeZeros(arr) {
  return arr.filter(notEquals(0));
}

removeZeros(acceptedTermsPoints()); // [3, 3]

DEMO演示

You can use Array#filter() with Boolean as callback.您可以使用Array#filter()Boolean作为回调。 This filters all values not like 0 or other falsy values.这将过滤所有与0或其他虚假值不同的值。

 var array = [0, 3, 3, 0, 0], result = array.filter(Boolean); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

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

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