从javascript数组中搜索元素列表的最佳方法

时间:2016-05-27 07:07:38

标签: javascript

下面是我的数组我要搜索名称“gali”,“john”和“joe”

var dummyArray =  [{
    "fname": "gali",
    "lname": "doe"
}, {
    "fname": "john",
    "lname": "danny"
}, {
    "fname": "joe",
    "lname": "dawns"
}, {
    "fname": "liji",
    "lname": "hawk"
}]

这样做的一种方法是使用grep和$ .each

   var searchcriteria['gali','john','joe'];
   var newArray = [];
   $(searchcriteria).each(function( index ) {
         var item= j$.grep(dummyArray , function(dt) {
         return (dt.fname== searchcriteria[index]);
   });
   newArray.push(item);
});

有更好的计划吗?

3 个答案:

答案 0 :(得分:4)

filter()

使用原生JavaScript indexOf() 方法

var dummyArray = [{
  "fname": "gali",
  "lname": "doe"
}, {
  "fname": "john",
  "lname": "danny"
}, {
  "fname": "joe",
  "lname": "dawns"
}, {
  "fname": "liji",
  "lname": "hawk"
}]

var searchcriteria = ['gali', 'john', 'joe'];
var newArray = dummyArray.filter(function(ele) {
  return searchcriteria.indexOf(ele.fname) > -1;
});

console.log(newArray);

将搜索值存储在对象中总是更好,因为 indexOf() 方法非常慢。

var dummyArray = [{
  "fname": "gali",
  "lname": "doe"
}, {
  "fname": "john",
  "lname": "danny"
}, {
  "fname": "joe",
  "lname": "dawns"
}, {
  "fname": "liji",
  "lname": "hawk"
}]

var searchcriteria = {'gali':true, 'john':true, 'joe':true};
var newArray = dummyArray.filter(function(ele) {
  return searchcriteria[ele.fname];
});

console.log(newArray);

答案 1 :(得分:3)

您可以使用.filter

var dummyArray =  [{
    "fname": "gali",
    "lname": "doe"
}, {
    "fname": "john",
    "lname": "danny"
}, {
    "fname": "joe",
    "lname": "dawns"
}, {
    "fname": "liji",
    "lname": "hawk"
}];

var searchcriteria = ['gali','john','joe'];
var output = dummyArray.filter(function(x){
 return  searchcriteria.indexOf(x.fname)!=-1
});

console.log(output)

答案 2 :(得分:3)

您可以将Array#filterArray#includesarrow functions一起使用。

dummyArray.filter(o => searchcriteria.includes(o.fname));



var dummyArray = [{
    "fname": "gali",
    "lname": "doe"
}, {
    "fname": "john",
    "lname": "danny"
}, {
    "fname": "joe",
    "lname": "dawns"
}, {
    "fname": "liji",
    "lname": "hawk"
}];

var searchcriteria = ['gali', 'john', 'joe'];

var result = dummyArray.filter(o => searchcriteria.includes(o.fname));
console.log(result);




对于不支持EcmaScript 6的旧版浏览器,等效代码为

dummyArray.filter(function (o) {
    return searchcriteria.indexOf(o.fname) !== -1;
});