检测数组中的对象是否具有与其他对象相同的属性但不同的其他属性

时间:2016-05-25 14:45:25

标签: javascript arrays

拿这个数组:

[
  {"color": "blue","type": 1},
  {"color": "red","type": 1},
  {"color": "blue","type": 1},
  {"color": "green","type": 1},
  {"color": "green","type": 1},
  {"color": "red","type": 2},
  {"color": "red","type": 1},
  {"color": "green","type": 2},
  {"color": "red","type": 3},
];

我将如何找到哪种颜色"有一个不同的"类型" (与阵列中具有相同"名称")的所有其他对象相比?

我希望能够遍历这个数组并创建一个如下所示的第二个数组:

{red, green}

注意蓝色被省略,因为所有的对象都带有" color":" blue"有相同的"类型"

我得到的最接近的是:https://jsfiddle.net/0wgjs5zh/但是它会将所有颜色添加到附加了不同类型的数组中:

arr.forEach(function(item){
  if(newArr.hasOwnProperty(item.color+ '-' +item.type)) {
   // newArr[item.color+ '-' +item.type].push(item);
  }
  else {
    newArr[item.color+ '-' +item.type] = item;
  }
});

// RESULT
{blue-1, green-1, green-2, red-1, red-2, red-3}

2 个答案:

答案 0 :(得分:4)

您可以使用两个通道,一个用于集合,另一个用于生成结果数组。



var array = [{ "color": "blue", "type": 1 }, { "color": "red", "type": 1 }, { "color": "blue", "type": 1 }, { "color": "green", "type": 1 }, { "color": "green", "type": 1 }, { "color": "red", "type": 2 }, { "color": "red", "type": 1 }, { "color": "green", "type": 2 }, { "color": "red", "type": 3 }, ],
    result,
    object = Object.create(null);

array.forEach(function (a) {
    object[a.color] = object[a.color] || {};
    object[a.color][a.type] = true;
});

result = Object.keys(object).filter(function (k) {
    return Object.keys(object[k]).length > 1;
});

console.log(result);




答案 1 :(得分:0)

我的解决方案如下



var cls = [
  {"color": "blue","type": 1},
  {"color": "red","type": 1},
  {"color": "blue","type": 1},
  {"color": "green","type": 1},
  {"color": "green","type": 1},
  {"color": "red","type": 2},
  {"color": "red","type": 1},
  {"color": "green","type": 2},
  {"color": "red","type": 3},
],

    map = cls.reduce((p,c) => (p[c.color] ? !~p[c.color].indexOf(c.type) && p[c.color].push(c.type)
                                          : p[c.color] = [c.type], p),{}),
 result = Object.keys(map).reduce((p,c) => map[c].length > 1 && p.concat(c) || p,[]);

console.log(result);