JavaScript:删除共享相同属性值的对象的重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32238602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript: Remove duplicates of objects sharing same property value
提问by Lauren F
I have an array of objects that I would like to trim down based on a specific key:valuepair. I want to create an array that includes only one object per this specific key:valuepair. It doesn't necessarily matter which object of the duplicates is copied to the new array.
我有一组对象,我想根据特定的key:value对来修剪这些对象。我想创建一个数组,其中每个特定key:value对只包含一个对象。将重复项的哪个对象复制到新数组并不重要。
For example, I want to trim based on the priceproperty of arrayWithDuplicates, creating a new array that only includes one of each value:
例如,我想根据 的price属性进行修剪arrayWithDuplicates,创建一个仅包含每个值之一的新数组:
var arrayWithDuplicates = [
{"color":"red",
"size": "small",
"custom": {
"inStock": true,
"price": 10
}
},
{"color":"green",
"size": "small",
"custom": {
"inStock": true,
"price": 30
}
},
{"color":"blue",
"size": "medium",
"custom": {
"inStock": true,
"price": 30
}
},
{"color":"red",
"size": "large",
"custom": {
"inStock": true,
"price": 20
}
}
];
Would become:
会成为:
var trimmedArray = [
{"color":"red",
"size": "small",
"custom": {
"inStock": true,
"price": 10
}
},
{"color":"green",
"size": "small",
"custom": {
"inStock": true,
"price": 30
}
},
{"color":"red",
"size": "large",
"custom": {
"inStock": true,
"price": 20
}
}
];
Is there a JavaScript or Angular function that would loop through and do this?
是否有 JavaScript 或 Angular 函数可以循环执行此操作?
EDIT: The property to filter on is nested within another property.
编辑:要过滤的属性嵌套在另一个属性中。
采纳答案by user3335966
You can use underscorefor this:
您可以为此使用下划线:
//by size:
var uSize = _.uniqBy(arrayWithDuplicates, function(p){ return p.size; });
//by custom.price;
var uPrice = _.uniqBy(arrayWithDuplicates, function(p){ return p.custom.price; });
回答by Tamas Hegedus
This function removes duplicate values from an array by returning a new one.
此函数通过返回一个新值从数组中删除重复值。
function removeDuplicatesBy(keyFn, array) {
var mySet = new Set();
return array.filter(function(x) {
var key = keyFn(x), isNew = !mySet.has(key);
if (isNew) mySet.add(key);
return isNew;
});
}
var values = [{color: "red"}, {color: "blue"}, {color: "red", number: 2}];
var withoutDuplicates = removeDuplicatesBy(x => x.color, values);
console.log(withoutDuplicates); // [{"color": "red"}, {"color": "blue"}]
So you could use it like
所以你可以像这样使用它
var arr = removeDuplicatesBy(x => x.custom.price, yourArrayWithDuplicates);
回答by yvesmancera
I don't think there's a built-in function in Angular, but it isn't hard to create one:
我认为 Angular 中没有内置函数,但创建一个并不难:
function removeDuplicates(originalArray, objKey) {
var trimmedArray = [];
var values = [];
var value;
for(var i = 0; i < originalArray.length; i++) {
value = originalArray[i][objKey];
if(values.indexOf(value) === -1) {
trimmedArray.push(originalArray[i]);
values.push(value);
}
}
return trimmedArray;
}
Usage:
用法:
removeDuplicates(arrayWithDuplicates, 'size');
Returns:
返回:
[
{
"color": "red",
"size": "small"
},
{
"color": "blue",
"size": "medium"
},
{
"color": "red",
"size": "large"
}
]
And
和
removeDuplicates(arrayWithDuplicates, 'color');
Returns:
返回:
[
{
"color": "red",
"size": "small"
},
{
"color": "green",
"size": "small"
},
{
"color": "blue",
"size": "medium"
}
]
回答by gilly3
Use Array.filter(), keeping track of values by using an Objectas a hash, and filtering out any items whose value is already contained in the hash.
使用Array.filter(),通过将Object用作散列来跟踪值,并过滤掉其值已包含在散列中的任何项目。
function trim(arr, key) {
var values = {};
return arr.filter(function(item){
var val = item[key];
var exists = values[val];
values[val] = true;
return !exists;
});
}
回答by Mukesh Ranjan
You can use lodashto remove duplicate objects:
您可以使用lodash删除重复的对象:
import * as _ from 'lodash';
_.uniqBy(data, 'id');
Here 'id' is your unique identifier
这里“ id”是您的唯一标识符
回答by sliter
Try the following function:
试试下面的函数:
function trim(items){
const ids = [];
return items.filter(item => ids.includes(item.id) ? false : ids.push(item.id));
}
回答by sudha priya
for (let i = 0; i < arrayWithDuplicates.length; i++) {
for (let j = i + 1; j < arrayWithDuplicates.length; j++) {
if (arrayWithDuplicates[i].name === students[j].name) {
arrayWithDuplicates.splice(i, 1);
}
}
}
this will work perfectly...and this will delete first repeated array.
To delete last repeated array we only have to change
arrayWithDuplicates.splice(i, 1) ; into
arrayWithDuplicates.splice(j, 1);
回答by Souvik Basu
Simple solution although not the most performant:
简单的解决方案虽然不是最高效的:
var unique = [];
duplicates.forEach(function(d) {
var found = false;
unique.forEach(function(u) {
if(u.key == d.key) {
found = true;
}
});
if(!found) {
unique.push(d);
}
});
回答by yureka
using lodashyou can filter it out easily
使用lodash您可以轻松过滤掉它
the first parameter will be your array and second will be your field with duplicates
第一个参数将是您的数组,第二个参数将是您的重复字段
_.uniqBy(arrayWithDuplicates, 'color')
it will return an array with unique value
它将返回一个具有唯一值的数组
回答by Praveen M P
Here is the typescript way
这是打字稿方式
public removeDuplicates(originalArray:any[], prop) {
let newArray = [];
let lookupObject = {};
originalArray.forEach((item, index) => {
lookupObject[originalArray[index][prop]] = originalArray[index];
});
Object.keys(lookupObject).forEach(element => {
newArray.push(lookupObject[element]);
});
return newArray;
}
And
和
let output = this.removeDuplicates(yourArray,'color');

