오브젝트 배열에서 중복된 모든 것을 제거하려면 어떻게 해야 합니까?
개체 배열이 포함된 개체가 있습니다.
obj = {};
obj.arr = new Array();
obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
어레이에서 중복 개체를 제거하는 가장 좋은 방법이 무엇인지 궁금합니다.를 들어, '예'라고 하면obj.arr★★★★★★★★★★★...
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
좀 드시면 어떨까요?es6 마술?
obj.arr = obj.arr.filter((value, index, self) =>
index === self.findIndex((t) => (
t.place === value.place && t.name === value.name
))
)
보다 일반적인 솔루션은 다음과 같습니다.
const uniqueArray = obj.arr.filter((value, index) => {
const _value = JSON.stringify(value);
return index === obj.arr.findIndex(obj => {
return JSON.stringify(obj) === _value;
});
});
「」이 , 한다.JSON.stringify:
const isPropValuesEqual = (subject, target, propNames) =>
propNames.every(propName => subject[propName] === target[propName]);
const getUniqueItemsByProperties = (items, propNames) =>
items.filter((item, index, array) =>
index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
);
수 .propNames" " 열열열는열는 、 " 성성::
const getUniqueItemsByProperties = (items, propNames) => {
const propNamesArray = Array.from(propNames);
return items.filter((item, index, array) =>
index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))
);
};
다 허용getUniqueItemsByProperties('a') ★★★★★★★★★★★★★★★★★」getUniqueItemsByProperties(['a']);
설명.
- 먼저 사용되는 다음 두 가지 방법을 이해하십시오.
- 다음으로, 무엇이 두 물체를 동등하게 만드는지에 대한 아이디어를 가지고 그것을 명심하십시오.
- 만약 그것이 방금 생각한 기준을 충족한다면, 우리는 어떤 것이 중복되는 것을 탐지할 수 있지만, 그 기준이 있는 물체의 첫 번째 인스턴스가 아니다.
- 따라서 위의 기준을 사용하여 중복 여부를 판단할 수 있습니다.
필터 포함 라이너 1개(주문 유지)
「」id을 사용하다
arr.filter((v,i,a)=>a.findIndex(v2=>(v2.id===v.id))===i)
순서가 중요하지 않은 경우 맵 솔루션이 더 빠릅니다: 맵을 사용한 솔루션
속성에 의( 「」 「」 「」)place ★★★★★★★★★★★★★★★★★」name)
arr.filter((v,i,a)=>a.findIndex(v2=>['place','name'].every(k=>v2[k] ===v[k]))===i)
모든 속성에서 고유(대형 어레이의 경우 속도가 느림)
arr.filter((v,i,a)=>a.findIndex(v2=>(JSON.stringify(v2) === JSON.stringify(v)))===i)
대체하여 마지막 오카렌스를 유지합니다.findIndexfindLastIndex.
arr.filter((v,i,a)=>a.findLastIndex(v2=>(v2.place === v.place))===i)
ES6+를 한 줄로 사용하면 키별로 고유한 개체 목록을 얻을 수 있습니다.
const unique = [...new Map(arr.map((item, key) => [item[key], item])).values()]
다음과 같은 기능에 넣을 수 있습니다.
function getUniqueListBy(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
다음으로 작업 예를 제시하겠습니다.
const arr = [
{place: "here", name: "x", other: "other stuff1" },
{place: "there", name: "x", other: "other stuff2" },
{place: "here", name: "y", other: "other stuff4" },
{place: "here", name: "z", other: "other stuff5" }
]
function getUniqueListBy(arr, key) {
return [...new Map(arr.map(item => [item[key], item])).values()]
}
const arr1 = getUniqueListBy(arr, 'place')
console.log("Unique by place")
console.log(JSON.stringify(arr1))
console.log("\nUnique by name")
const arr2 = getUniqueListBy(arr, 'name')
console.log(JSON.stringify(arr2))
어떻게 작동합니까?
우선 맵의 입력으로 사용할 수 있도록 어레이를 다시 매핑한다.
arr.map(아이템=>[아이템[키], 아이템])
즉, 어레이의 각 항목이 2개의 요소로 이루어진 다른 배열로 변환됩니다.첫 번째 요소로 선택된 키와 두 번째 요소로 초기 항목 전체가 변환됩니다.이것은 엔트리(어레이 엔트리, 맵 엔트리 등)라고 불립니다.그리고 Map 컨스트럭터에서 어레이 엔트리를 추가하는 예를 보여주는 공식 문서를 소개합니다.
키가 배치되어 있는 경우의 예:
[["here", {place: "here", name: "x", other: "other stuff1" }], ...]
다음으로 이 수정된 배열을 맵 컨스트럭터에 전달하면 마법이 일어납니다.Map은 중복된 키 값을 제거하고 동일한 키의 마지막으로 삽입된 값만 유지합니다.주의: 맵은 삽입 순서를 유지합니다.(Map과 객체의 차이 확인)
new Map(위의 매핑된 엔트리 배열)
세 번째는 맵 값을 사용하여 원래 항목을 검색하지만 이번에는 중복되지 않습니다.
new Map(MappedArr.values)
마지막으로 이러한 값을 새로운 어레이에 추가하여 초기 구조처럼 보이게 하고 다음과 같은 값을 반환합니다.
[...new Map(MappedArr.values()]를 반환합니다.
기존 70개 이상의 답변보다 뛰어난 실행 시간을 갖춘 심플하고 고성능 솔루션:
const ids = array.map(o => o.id)
const filtered = array.filter(({id}, index) => !ids.includes(id, index + 1))
예:
const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 1, name: 'one'}]
const ids = arr.map(o => o.id)
const filtered = arr.filter(({id}, index) => !ids.includes(id, index + 1))
console.log(filtered)
구조:
Array.filter() 는 이전에 매핑된 id-array에 현재 ID가 포함되어 있는지 여부를 체크함으로써 모든 중복 개체를 삭제합니다( ).{id}는 오브젝트를 해당 id로만 파기합니다).실제 중복만 필터링하려면 의 두 번째 파라미터를 사용합니다.fromIndexindex + 1현재 개체와 이전 개체는 모두 무시됩니다.
되고 있기 filter는 이전에 않은 합니다.이것에 의해, 이전에 필터링 되지 않은 오브젝트만이 체크되기 때문에, 실행 시간이 큰폭으로 단축됩니다.
은 분명히 할 수 .id 키 키 , , , , , , , , , , , , , , , , , , , , , , , , , , 모든 키.
기본적인 방법은 다음과 같습니다.
const obj = {};
for (let i = 0, len = things.thing.length; i < len; i++) {
obj[things.thing[i]['place']] = things.thing[i];
}
things.thing = new Array();
for (const key in obj) {
things.thing.push(obj[key]);
}
만약 당신이 밑줄이나 lodash와 같은 Javascript 라이브러리를 사용할 수 있다면, 나는 다음 사이트를 볼 것을 권장합니다._.uniq도서관에서 기능하다.기능을 합니다.터에서lodash::::
_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])
기본적으로 객체 리터럴이 포함된 어레이를 전달하고 원래 데이터 어레이에서 중복을 제거할 속성을 전달합니다.이러한 속성은 다음과 같습니다.
var data = [{'name': 'Amir', 'surname': 'Rahnama'}, {'name': 'Amir', 'surname': 'Stevens'}];
var non_duplidated_data = _.uniq(data, 'name');
업데이트: Lodash는 현재.uniqBy뿐만 아니라.뿐만 아니라.
단일 필드의 중복을 기반으로 배열 내의 중복 개체를 제거하는 것과 동일한 요구 사항이 있었습니다.코드를 찾았습니다. Javascript: 개체 배열에서 중복 제거
따라서 이 예에서는 중복된 licenseNum 문자열 값이 있는 개체를 어레이에서 제거합니다.
var arrayWithDuplicates = [
{"type":"LICENSE", "licenseNum": "12345", state:"NV"},
{"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
{"type":"LICENSE", "licenseNum": "12345", state:"OR"},
{"type":"LICENSE", "licenseNum": "10849", state:"CA"},
{"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
{"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];
function removeDuplicates(originalArray, prop) {
var newArray = [];
var lookupObject = {};
for(var i in originalArray) {
lookupObject[originalArray[i][prop]] = originalArray[i];
}
for(i in lookupObject) {
newArray.push(lookupObject[i]);
}
return newArray;
}
var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));
결과:
unique Array:
[{"type":"LICENSE","licenseNum":"10849","state":"CA"},
{"type":"LICENSE","licenseNum":"12345","state":"NM"},
{"type":"LICENSE","licenseNum":"A7846","state":"CA"},
{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]
세트를 사용한 라이너 1개
var things = new Object();
things.thing = new Array();
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});
// assign things.thing to myData for brevity
var myData = things.thing;
things.thing = Array.from(new Set(myData.map(JSON.stringify))).map(JSON.parse);
console.log(things.thing)
설명:
new Set(myData.map(JSON.stringify))는 문자열화된 myData 요소를 사용하여 Set 객체를 만듭니다.- set object는 모든 요소가 고유함을 보증합니다.
- 그런 다음 Array.from을 사용하여 작성된 세트의 요소를 기반으로 배열을 만듭니다.
- 마지막으로 JSON.parse를 사용하여 문자열화된 요소를 개체로 변환합니다.
ES6 라이너 1대 있음
let arr = [
{id:1,name:"sravan ganji"},
{id:2,name:"pinky"},
{id:4,name:"mammu"},
{id:3,name:"avy"},
{id:3,name:"rashni"},
];
console.log(Object.values(arr.reduce((acc,cur)=>Object.assign(acc,{[cur.id]:cur}),{})))
되는 것을 합니다.filter:
var uniq = {};
var arr = [{"id":"1"},{"id":"1"},{"id":"2"}];
var arrFiltered = arr.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));
console.log('arrFiltered', arrFiltered);
개체의 한 필드만 비교해야 하는 경우 Array 반복 방법을 사용하여 이를 수행할 수 있는 또 다른 옵션이 있습니다.
function uniq(a, param){
return a.filter(function(item, pos, array){
return array.map(function(mapItem){ return mapItem[param]; }).indexOf(item[param]) === pos;
})
}
uniq(things.thing, 'place');
일반적인 방법은 배열의 두 요소가 동일한지 여부를 테스트하는 함수를 통과시키는 것입니다.하다', '비교하다', '비교하다'의 .name ★★★★★★★★★★★★★★★★★」place비교되는 두 개체의 속성.
ES5 답변
function removeDuplicates(arr, equals) {
var originalArr = arr.slice(0);
var i, len, val;
arr.length = 0;
for (i = 0, len = originalArr.length; i < len; ++i) {
val = originalArr[i];
if (!arr.some(function(item) { return equals(item, val); })) {
arr.push(val);
}
}
}
function thingsEqual(thing1, thing2) {
return thing1.place === thing2.place
&& thing1.name === thing2.name;
}
var things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
removeDuplicates(things, thingsEqual);
console.log(things);
오리지널 ES3 답변
function arrayContains(arr, val, equals) {
var i = arr.length;
while (i--) {
if ( equals(arr[i], val) ) {
return true;
}
}
return false;
}
function removeDuplicates(arr, equals) {
var originalArr = arr.slice(0);
var i, len, j, val;
arr.length = 0;
for (i = 0, len = originalArr.length; i < len; ++i) {
val = originalArr[i];
if (!arrayContains(arr, val, equals)) {
arr.push(val);
}
}
}
function thingsEqual(thing1, thing2) {
return thing1.place === thing2.place
&& thing1.name === thing2.name;
}
removeDuplicates(things.thing, thingsEqual);
중복을 모두 추가할 때까지 기다릴 수 있는 경우 일반적인 방법은 먼저 어레이를 정렬한 후 중복을 제거하는 것입니다.정렬을 통해 각 요소를 살펴볼 때 각 요소의 배열을 스캔하는 N * N 접근 방식을 피할 수 있습니다.
"복제 제거" 함수는 보통 unique 또는 uniq라고 불립니다.일부 기존 구현은 두 단계를 결합할 수 있습니다(예: 프로토타입의 uniq).
이 투고에는 시도해 볼 만한 아이디어가 거의 없습니다(및 회피할 수 있는 아이디어도 있습니다).라이브러리에 아직 없습니다.개인적으로는 이것이 가장 간단하다고 생각합니다.
function unique(a){
a.sort();
for(var i = 1; i < a.length; ){
if(a[i-1] == a[i]){
a.splice(i, 1);
} else {
i++;
}
}
return a;
}
// Provide your own comparison
function unique(a, compareFunc){
a.sort( compareFunc );
for(var i = 1; i < a.length; ){
if( compareFunc(a[i-1], a[i]) === 0){
a.splice(i, 1);
} else {
i++;
}
}
return a;
}
1대의 라이너(고성능, 순서를 유지하지 않음)
「」id 배열되어 있다arr.
const arrUniq = [...new Map(arr.map(v => [v.id, v])).values()]
순서가 중요한 경우 필터 포함 솔루션 확인: 필터 포함 솔루션
속성에 의( 「」 「」 「」)place ★★★★★★★★★★★★★★★★★」name의 )를 참조해 주세요arr
const arrUniq = [...new Map(arr.map(v => [JSON.stringify([v.place,v.name]), v])).values()]
내의 arr
const arrUniq = [...new Map(arr.map(v => [JSON.stringify(v), v])).values()]
오카렌스를 배열로 합니다.arr
const arrUniq = [...new Map(arr.slice().reverse().map(v => [v.id, v])).values()].reverse()
가장 좋은 방법은 reduce and Map 객체를 사용하는 것이라고 생각합니다.이것은 단일 회선 솔루션입니다.
const data = [
{id: 1, name: 'David'},
{id: 2, name: 'Mark'},
{id: 2, name: 'Lora'},
{id: 4, name: 'Tyler'},
{id: 4, name: 'Donald'},
{id: 5, name: 'Adrian'},
{id: 6, name: 'Michael'}
]
const uniqueData = [...data.reduce((map, obj) => map.set(obj.id, obj), new Map()).values()];
console.log(uniqueData)
/*
in `map.set(obj.id, obj)`
'obj.id' is key. (don't worry. we'll get only values using the .values() method)
'obj' is whole object.
*/
고려중
const objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
얘들아, 이걸 뭉개버리자, 어때?
let uniqIds = {}, source = [{id:'a'},{id:'b'},{id:'c'},{id:'b'},{id:'a'},{id:'d'}];
let filtered = source.filter(obj => !uniqIds[obj.id] && (uniqIds[obj.id] = true));
console.log(filtered);
// EXPECTED: [{id:'a'},{id:'b'},{id:'c'},{id:'d'}];
목록에 하나 더 추가하다. 및 ES6 사용방법 »Array.reduceArray.find.
에서는 을 기반으로 .guid★★★★★★★★★★★★★★★★★★.
let filtered = array.reduce((accumulator, current) => {
if (! accumulator.find(({guid}) => guid === current.guid)) {
accumulator.push(current);
}
return accumulator;
}, []);
특성을 선택하고 하나의 라이너로 압축할 수 있도록 확장:
const uniqify = (array, key) => array.reduce((prev, curr) => prev.find(a => a[key] === curr[key]) ? prev : prev.push(curr) && prev, []);
이를 사용하려면 문자열 값으로 개체 배열과 중복 제거할 키의 이름을 전달합니다.
const result = uniqify(myArrayOfObjects, 'guid')
,도할 수 .Map:
const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());
전체 샘플:
const things = new Object();
things.thing = new Array();
things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});
const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());
console.log(JSON.stringify(dedupThings, null, 4));
결과:
[
{
"place": "here",
"name": "stuff"
},
{
"place": "there",
"name": "morestuff"
}
]
TypeScript 솔루션
이렇게 하면 중복 개체가 제거되고 개체 유형도 보존됩니다.
function removeDuplicateObjects(array: any[]) {
return [...new Set(array.map(s => JSON.stringify(s)))]
.map(s => JSON.parse(s));
}
let myData = [{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}];
let q = [...new Map(myData.map(obj => [JSON.stringify(obj), obj])).values()];
console.log(q)
및 ES6를 new Map().
// assign things.thing to myData
let myData = things.thing;
[...new Map(myData.map(obj => [JSON.stringify(obj), obj])).values()];
상세:-
.map()합니다.[key, value]array(첫 요소는 pair array(키)입니다.stringified및 는 second(값)가 .object그 자체입니다.- 을 에 추가합니다.
new Map()를 있다stringified오브젝트 및 동일한 키를 추가하면 기존 키가 덮어쓰게 됩니다. - 「」를 사용합니다.
.values()맵 을 부여합니다(MapIterator).obj★★★★★★★★★★★★★★★★★」 - ㅇㅇㅇㅇㅇ.
spread ...연산자를 지정하면 새 배열에 위 단계의 값을 지정할 수 있습니다.
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filteredArr = things.reduce((thing, current) => {
const x = thing.find(item => item.place === current.place);
if (!x) {
return thing.concat([current]);
} else {
return thing;
}
}, []);
console.log(filteredArr)
Via ★★★★★★Set| | 데이터 타입에 따라
const seen = new Set();
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filteredArr = things.filter(el => {
const duplicate = seen.has(el.place);
seen.add(el.place);
return !duplicate;
});
console.log(filteredArr)
Set
Set Object의 각 값은 고유해야 합니다. 값의 동일성이 확인됩니다.
에 따라 인지 오브젝트 it인지에 의 인스턴스 .Set는 Set(Purpose of Set)의 Set(Purpose of Set)에 유용합니다.add,clear,has&delete.
고유 및 데이터 유형 기능:..
add
기본적으로는 고유한 데이터를 수집에 푸시하여 데이터 유형도 유지합니다.즉, 중복 항목을 수집에 푸시하지 않도록 하고 기본적으로 데이터 유형을 검사합니다.
has
데이터 아이템이 컬렉션에 존재하는지 확인해야 할 때가 있습니다.또한 컬렉션에서 고유한 ID 또는 아이템과 데이터 유형을 확인하는 편리한 방법입니다.
delete
데이터 유형을 식별하여 컬렉션에서 특정 항목을 제거합니다.
clear
특정 변수에서 모든 컬렉션 항목을 제거하고 빈 개체로 설정합니다.
Set오브젝트에는 반복 메서드 및 기타 기능도 있습니다.
여기서 읽는 것이 좋다: 세트 - JavaScript | MDN
removeDuplicates()는 오브젝트 배열을 가져와 중복된 오브젝트 없이 새 어레이를 반환합니다(ID 속성에 기반).
const allTests = [
{name: 'Test1', id: '1'},
{name: 'Test3', id: '3'},
{name: 'Test2', id: '2'},
{name: 'Test2', id: '2'},
{name: 'Test3', id: '3'}
];
function removeDuplicates(array) {
let uniq = {};
return array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true))
}
removeDuplicates(allTests);
예상 결과:
[
{name: 'Test1', id: '1'},
{name: 'Test3', id: '3'},
{name: 'Test2', id: '2'}
];
먼저 변수 uniq 값을 빈 객체로 설정합니다.
다음으로 오브젝트 배열을 필터링합니다.필터는 제공된 함수에 의해 구현된 테스트를 통과한 모든 요소를 사용하여 새 배열을 만듭니다.
return array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));
위에서는 &&의 단락 기능을 사용합니다.&&의 왼쪽이 true로 평가되면 &&의 오른쪽 값이 반환됩니다.왼쪽이 false일 경우 &&의 왼쪽이 반환됩니다.
id 값이라는 이 경우 첫 번째 을 합니다).이 경우 obj.id은 uniq를 체크합니다.것(false 중 하나)과, 「true」(true) 「false」(false) 「false」(false!)로합니다.!uniq[obj.id] 속성을 경우 falseuniq id false(!) true를 「 obj.id 」 、 「 false 」 、 「 false 」 true ( ! 로q [ obj.id ]= true ) 。이 값은 필터 메서드에 해당 obj를 반환된 어레이에 추가하도록 지시하는 truthy 값이며 {1: true} 속성도 uniq에 추가합니다.그러면 동일한 ID를 가진 다른 obj 인스턴스가 다시 추가되지 않습니다.
이 방법이 효과적입니다.
function arrayUnique(arr, uniqueKey) {
const flagList = new Set()
return arr.filter(function(item) {
if (!flagList.has(item[uniqueKey])) {
flagList.add(item[uniqueKey])
return true
}
})
}
const data = [
{
name: 'Kyle',
occupation: 'Fashion Designer'
},
{
name: 'Kyle',
occupation: 'Fashion Designer'
},
{
name: 'Emily',
occupation: 'Web Designer'
},
{
name: 'Melissa',
occupation: 'Fashion Designer'
},
{
name: 'Tom',
occupation: 'Web Developer'
},
{
name: 'Tom',
occupation: 'Web Developer'
}
]
console.table(arrayUnique(data, 'name'))// work well
인쇄하다.
┌─────────┬───────────┬────────────────────┐
│ (index) │ name │ occupation │
├─────────┼───────────┼────────────────────┤
│ 0 │ 'Kyle' │ 'Fashion Designer' │
│ 1 │ 'Emily' │ 'Web Designer' │
│ 2 │ 'Melissa' │ 'Fashion Designer' │
│ 3 │ 'Tom' │ 'Web Developer' │
└─────────┴───────────┴────────────────────┘
ES5:
function arrayUnique(arr, uniqueKey) {
const flagList = []
return arr.filter(function(item) {
if (flagList.indexOf(item[uniqueKey]) === -1) {
flagList.push(item[uniqueKey])
return true
}
})
}
이 두 가지 방법은 더 간단하고 이해하기 쉽다.
다음은 마지막 항목만 보관하고 싶은 ES6용 솔루션입니다.이 솔루션은 기능적으로 Airbnb 스타일에 준거하고 있습니다.
const things = {
thing: [
{ place: 'here', name: 'stuff' },
{ place: 'there', name: 'morestuff1' },
{ place: 'there', name: 'morestuff2' },
],
};
const removeDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]
느린 타이프스크립트 개발자를 위한 빠르고 안전한 답변:
export const uniqueBy = <T>( uniqueKey: keyof T, objects: T[]): T[] => {
const ids = objects.map(object => object[uniqueKey]);
return objects.filter((object, index) => !ids.includes(object[uniqueKey], index + 1));
}
이 질문에는 이미 많은 답이 있다는 것을 알지만, 조금만 참아주세요...
어레이 내의 일부 개체에는 관심이 없는 추가 속성이 있거나 속성의 하위 집합만 고려하여 원하는 개체가 있을 수 있습니다.
하다를 찾고 .이러한 개체"만 할 수 있습니다.propOne ★★★★★★★★★★★★★★★★★」propTwo그 외의 속성은 무시해 주세요.
예상된 결과에는 처음 개체와 마지막 개체만 포함됩니다.코드는 다음과 같습니다.
const array = [{
propOne: 'a',
propTwo: 'b',
propThree: 'I have no part in this...'
},
{
propOne: 'a',
propTwo: 'b',
someOtherProperty: 'no one cares about this...'
},
{
propOne: 'x',
propTwo: 'y',
yetAnotherJunk: 'I am valueless really',
noOneHasThis: 'I have something no one has'
}];
const uniques = [...new Set(
array.map(x => JSON.stringify(((o) => ({
propOne: o.propOne,
propTwo: o.propTwo
}))(x))))
].map(JSON.parse);
console.log(uniques);
다른 옵션은 각 개체에 대해 선택한 속성 값을 비교하여 축소 함수로 래핑하는 사용자 지정 indexOf 함수를 생성하는 것입니다.
var uniq = redundant_array.reduce(function(a,b){
function indexOfProperty (a, b){
for (var i=0;i<a.length;i++){
if(a[i].property == b.property){
return i;
}
}
return -1;
}
if (indexOfProperty(a,b) < 0 ) a.push(b);
return a;
},[]);
여기서 reduce 메서드를 사용하여 객체 배열에서 중복을 제거하는 간단한 솔루션을 찾았습니다.객체의 위치 키를 기준으로 요소를 필터링하고 있습니다.
const med = [
{name: 'name1', position: 'left'},
{name: 'name2', position: 'right'},
{name: 'name3', position: 'left'},
{name: 'name4', position: 'right'},
{name: 'name5', position: 'left'},
{name: 'name6', position: 'left1'}
]
const arr = [];
med.reduce((acc, curr) => {
if(acc.indexOf(curr.position) === -1) {
acc.push(curr.position);
arr.push(curr);
}
return acc;
}, [])
console.log(arr)
ES6:thisArg에 대한 의론.new Set 대체 이 있습니다.즉, 에는 적절한 방법이 있습니다.
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filtered = things.filter(function({place, name}) {
const key =`${place}${name}`;
return !this.has(key) && this.add(key);
}, new Set);
console.log(filtered);
기능으로는 .() => ~로this이치노
언급URL : https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects
'source' 카테고리의 다른 글
| MariaDB: 알 수 없는 데이터 유형 "MYSql_JSON" (0) | 2022.11.21 |
|---|---|
| 미포함(약속)TypeError: 'in' 연산자를 사용하여 다음 위치에서 'validateStatus'를 검색할 수 없습니다. (0) | 2022.11.21 |
| Vuex Typescript Component.ts 파일에 "Member 'someMutation'에 암묵적으로 'any' type이 있습니다."라는 오류가 표시됨 (0) | 2022.11.21 |
| 정렬된 컬렉션과 정렬된 컬렉션의 차이점은 무엇입니까? (0) | 2022.11.21 |
| MariaDB는 중첩된 트랜잭션을 지원합니까? (0) | 2022.11.21 |