在JavaScript中,从数组中删除“错误”值的最有效方法是什么?

时间:2019-03-20 18:27:37

标签: javascript arrays

我正在尝试从性能上找出最佳方法。

鉴于以下问题;

您有一个数字数组,另一个有要从第一个数组中删除的数字。

我尝试了几件事:https://codepen.io/bluebrown/pen/VRGgpm

 select HOSP_DISCH_TIME, HOSP_ADMSN_TIME, (HOSP_DISCH_TIME- 
 HOSP_ADMSN_TIME)as 
 Days 
 from PAT_ENC_HSP;

然后:https://codepen.io/bluebrown/pen/GeXwBL?editors=0012

let dataArray = [2,4,5,8,1,9,3];
let blackList = [3,5,8,7];

function findFaulty(data, bad) {
  if (bad.length > 0) {
    let cleanData = [];
    data.forEach(item => {
      let x = 0;
      bad.forEach(b => {
        if (b === item) return;
        x++;
        if (x >= bad.length) cleanData.push(item);
      });
    });
    return cleanData;  
  }
  return data;
};

console.log(findFaulty(dataArray, blackList));

最后:https://codepen.io/bluebrown/pen/EMdyVg

let dataArray = [2, 4, 5, 8, 1, 9, 3];
let blackList = [2, 3];

function filterData(data, bad) {
    bad.forEach((b, i, a) => a[i] = data.indexOf(b));
    bad.filter(x => x > -1).forEach((b, i) => data.splice(b, 1, -1));
    return data.filter(d => d > -1)
};

console.log(filterData(dataArray, blackList));

2 个答案:

答案 0 :(得分:2)

您可以从末尾迭代数组并拼接找到的项目。

function filter(items, remove) {
    var i = items.length;
    while (i--) {
        if (remove.includes(items[i])) items.splice(i, 1);
    }
    return items;
}

console.log(...filter([2, 4, 5, 8, 1, 9, 3], [3, 5, 8, 7]));

答案 1 :(得分:1)

使用现有数据格式,您可以使用过滤器和包含。

let dataArray = [2,4,5,8,1,9,3];
let blackList = [3,5,8,7];

let op = dataArray.filter(e=> !blackList.includes(e))

console.log(op)

但是IMO最高效的方式将使用blackList作为对象,

let dataArray = [2,4,5,8,1,9,3];
let blackList = {3:false,5:false,8:false,7:false};

let op = dataArray.filter(e=> blackList[e] !== false)

console.log(op)