将字符串与对象数组进行比较

时间:2017-05-04 23:03:32

标签: javascript

我想出了这个解决方案来比较一个字符串和一个对象数组。但是,我不认为这是最好的解决方案。关于如何使这个函数对大型对象更好的建议?



var a = "blAh";
var b = [{
  "tag": "tag1",
  "icons": ["blah"]
}, {
  "tag": "tag2",
  "icons": ["Blah", "apple", "banana", "bLaH"]
}];

// Desired output "tag1, tag2"
function getTitle(tags, icon) {
  let arr = [];
  for (var i = 0; i < tags.length; i++) {
    tags[i].icons.forEach(elem => {
      if (icon.toLowerCase() === elem.toLowerCase()) {
        if (!arr.includes(tags[i].tag)) {
          arr.push(tags[i].tag);
        }
      }
    });
  }

  return arr.join(', ');
}
console.log(getTitle(b, a));
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

为了便于阅读,我将使用以下内容:

var res = b.filter(el =>
  el.icons.length < 0 
    ? false
    : el.icons.map(icon =>  icon.toLowerCase()).indexOf(a.toLocaleLowerCase()) != -1
).map(el => el.tag).join(', ');

但是对于表演来说,这个会更好:

var res = [];
var i, j;
for (i = 0; i < b.length; i++) {
  if (b[i].icons.length < 0) {
  } else {
     for (j = 0; j < b[i].icons.length; j++)
       b[i].icons[j] = b[i].icons[j].toLowerCase();
    if (b[i].icons.indexOf(a.toLocaleLowerCase()) !== -1)
      res.push(b[i].tag);
  }
}
res = res.join(', ');

原因如下:

  • indexOf总是比includes更快(或者在旧版Chrome中相同)。 benchmark
  • for循环总是比filter,map或reduce等数组方法更快。基准:mapfilter

同样有意见for loops are faster than indexOf in the latest version of chrome (60)

希望它有所帮助,
最好的问候

相关问题