拿着这个数组:
[
{"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}请注意,蓝色是通用的,因为所有具有“颜色”的对象都有相同的“类型”。
我得到的最接近的是: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}发布于 2016-05-25 14:57:08
您可以使用两次传递,一次用于集合,一次用于生成结果数组。
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);
发布于 2016-05-25 15:19:23
我的解决方案如下所示
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);
https://stackoverflow.com/questions/37440579
复制相似问题