筛选数组以创建另一个数组的最佳方法是什么?

时间:2012-01-29 03:14:33

标签: javascript arrays filtering

我想基于字符串过滤数组中的项目并将它们保存到新数组,然后在第二个数组上执行其他一些函数。我怎样才能做到最好?

这是我到目前为止所拥有的。

for (var i = 0; i < array.length; i++) {
    var num = i;
    var item = array.entries[i];
    var str = item.content;    
    var newArray = new Array();

    if (str.indexOf("filter") !== -1) {
                // If the content of the item contains a given string then ad it to the array.
                newArray.push(item);

        if (num === array.length) {
            // When we reach the end of the first array, perform something on the new array.
            doSomeFunction();
        }
    }

    function doSomeFunction() {
        // Now do something with the new array
        for (var j = 0; j < newArray.length; j++) {
            // Blah, blah, blah...
        }
    }
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

ECMAScript 5支持数组上的filter方法。

例如:

> [1,2,3,4].filter(function(v) { return v % 2 == 0})
[ 2, 4 ]

您可以参考MDN's document查看用法。

但请注意,某些浏览器不支持此功能,出于兼容性问题,您可以考虑使用es5-shimunderscore

在你的情况下对字符串数组进行工作。您可以将filtermap

一起使用

例如,要过滤以'index'开头的所有字符串,然后从中获取尾随数字。

var ss = [
  "index1",
  "index2",
  "index3",
  "foo4",
  "bar5",
  "index6"
];

var nums = ss.filter(function(s) {
  return /^index/.test(s);
}).map(function(s) {
  return parseInt(s.match(/(\d+)$/)[1], 10);
});

console.log(nums);

上面的脚本为您提供了[1,2,3,6]

答案 1 :(得分:0)

这样的事情:

function arrayFromArray(a,f){
  var b=[];
  for (var x=0;x<a.length;x++) {
    if (f(a[x])) {
      b.push(a[x]);
    }
  }
  return b;
}


function predicateIsEven(i){
  return i%2==0;
}


var arr=[1,2,3,4,5,6];

var evens=arrayFromArray(arr,predicateIsEven);