尝试通过比较两个其他值来创建新数组时避免重复

时间:2017-06-01 17:12:17

标签: javascript arrays

我有一个应用程序,我需要通过在比较一个数组中存在于另一个数组中的值之后推送来自其他两个数组的值来创建新数组。

实施例: 从这两个阵列......

sel[1,4];

bus[1,2,3,4,5,6];

所需的结果是一个新的对象数组,它将在我的视图中填充复选框的转发器......

newList[{1:true},{2:false},{3:false},{4:true},{5:false},{6:false}];

我遇到的问题是,我的代码正在创建重复项,而我却没有看到原因。

这是我的代码:

  var newList = [];
  var bus = self.businesses;
  var sel = self.campaign.data.businesses;



  for( var b = 0; b < bus.length; b++ ){
    if(sel.length > -1){
      for( var s = 0; s < sel.length; s++){
          if( bus[b]._id === sel[s].business_id){
            newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':true});
          } else {
            newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
          }
      }
    } else {
      console.log('hit else statement');
      newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
    }
  }

我需要新鲜的眼睛,因为它对我来说是正确的......但显然我错过了一些东西。 : - )

4 个答案:

答案 0 :(得分:2)

您的代码会生成重复项,因为每次运行内部循环并且ID不匹配时,您会将selected: false个对象推送到newList

for( var s = 0; s < sel.length; s++){
    if( bus[b]._id === sel[s].business_id){
        newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':true});
    } else {
        // THIS LINE CAUSES THE DUPLICATES:
        newList.push({'business_id':bus[b]._id, 'name':bus[b].business_name, 'selected':false});
    }
}

要修复代码,请将此行从内循环移到下面的外循环中,并将continue outer;添加到内循环的if正文中。然后,您需要将outer标签直接放在外部循环的前面:outer: for( var b = 0; b < bus.length; b++ ) ...

但是,我建议更简单的实现如下:

let selection = [{_id: 1, business_name: 'A'}];
let businesses = [{_id: 1, business_name: 'A'}, {_id: 2, business_name: 'B'}];

let result = businesses.map(business => ({
   'business_id': business._id,
   'name': business.business_name,
   'selected': selection.some(selected => business._id == selected._id)
}));

console.log(result);

附录:与传统功能相同的实现:

var selection = [{_id: 1, business_name: 'A'}];
var businesses = [{_id: 1, business_name: 'A'}, {_id: 2, business_name: 'B'}];

var result = businesses.map(function(business) {
  return {
    'business_id': business._id,
    'name': business.business_name,
    'selected': selection.some(function(selected) { return business._id == selected._id })
  };
});

console.log(result);

答案 1 :(得分:1)

我建议使用不同的方法,使用sel的对象,并使用值为新数组迭代bus

&#13;
&#13;
function getArray(items, selected) {
    var hash = Object.create(null);
    selected.forEach(function (a) {
        hash[a] = true;
    });
    return items.map(function (a) {
        var temp = {};
        temp[a] = hash[a] || false;
        return temp;
    });
}

console.log(getArray([1, 2, 3, 4, 5, 6], [1, 4]));
&#13;
&#13;
&#13;

ES6与Set

&#13;
&#13;
function getArray(items, selected) {
    return items.map((s => a => ({ [a]: s.has(a) }))(new Set(selected)));
}

console.log(getArray([1, 2, 3, 4, 5, 6], [1, 4]));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以在总线阵列上使用map()方法,并使用includes()检查sel数组中是否存在当前值。

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

var result = bus.map(e => ({[e] : sel.includes(e)}))
console.log(result)

答案 3 :(得分:0)

这将Nina Scholz优雅的ES6方法与le_m更具体的解决方案相结合,为您提供更短,多功能和可重复使用的功能。

&#13;
&#13;
function getArray(items, selected, [...id] = selected.map(selector => selector._id)) {
  return [items.map((s => a => ({
    [a._id + a.business_name]: s.has(a._id)
  }))(new Set(id)))];
}

console.log(...getArray([{
  _id: 1,
  business_name: 'A'
}, {
  _id: 2,
  business_name: 'B'
}, {
  _id: 3,
  business_name: 'C'
}, {
  _id: 4,
  business_name: 'D'
}, {
  _id: 5,
  business_name: 'E'
}, {
  _id: 6,
  business_name: 'F'
}], [{
  _id: 1,
  business_name: 'A'
}, {
  _id: 2,
  business_name: 'B'
}]));
&#13;
&#13;
&#13;