如果对象值在数组中是唯一的,则执行此操作
If object value is unique in array, do this
如果我有一个对象数组
[
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: false, occupation: "barber"}
]
(这个数组很大),我想确定哪些职业是唯一的,在这种情况下 return 一个新数组,其中只有布尔值 isunique 像这样改变:
[
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: true, occupation: "barber"}
]
这是否可以在 Javascript 中使用大数组高效地完成?我在这里完全不知所措。
您可以遍历数组并根据是否有任何其他对象具有相同的职业来更改 isunique
属性,像这样
arr.forEach(function(item) {
item.isunique = !arr.some(function(item2) {
return item !== item2 && item.occupation === item2.occupation;
});
});
var arr = [
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: false, occupation: "barber"}
]
arr.forEach(function(item) {
item.isunique = !arr.some(function(item2) {
return item !== item2 && item.occupation === item2.occupation;
});
});
document.body.innerHTML = '<pre>' + JSON.stringify(arr, null, 4) + '</pre>'
一个选项是:
var count = data.reduce(function(ret, el) {
ret[el.occupation] = (ret[el.occupation] || 0) + 1;
return ret;
}, {});
data.forEach(function(el) { el.isunique = count[el.occupation] === 1; });
如果我有一个对象数组
[
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: false, occupation: "barber"}
]
(这个数组很大),我想确定哪些职业是唯一的,在这种情况下 return 一个新数组,其中只有布尔值 isunique 像这样改变:
[
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: true, occupation: "barber"}
]
这是否可以在 Javascript 中使用大数组高效地完成?我在这里完全不知所措。
您可以遍历数组并根据是否有任何其他对象具有相同的职业来更改 isunique
属性,像这样
arr.forEach(function(item) {
item.isunique = !arr.some(function(item2) {
return item !== item2 && item.occupation === item2.occupation;
});
});
var arr = [
{name: 'John', count: 5, isunique: false, occupation: 'carpenter'},
{name: 'Bob', count: 6, isunique: false, occupation: 'carpenter'},
{name: "John", count: 9, isunique: false, occupation: "barber"}
]
arr.forEach(function(item) {
item.isunique = !arr.some(function(item2) {
return item !== item2 && item.occupation === item2.occupation;
});
});
document.body.innerHTML = '<pre>' + JSON.stringify(arr, null, 4) + '</pre>'
一个选项是:
var count = data.reduce(function(ret, el) {
ret[el.occupation] = (ret[el.occupation] || 0) + 1;
return ret;
}, {});
data.forEach(function(el) { el.isunique = count[el.occupation] === 1; });