javascript object array remove duplicates by property

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

javascript object array remove duplicates by property

영리치 0 907 2023.02.01 09:44

To remove duplicates from a JavaScript array of objects based on a specific property, you can use the reduce() method along with the findIndex() method:


let arr = [{a: 1, b: 'foo'}, {a: 2, b: 'bar'}, {a: 1, b: 'baz'}, {a: 3, b: 'qux'}];

let uniqueArr = arr.reduce((acc, curr) => {

  let index = acc.findIndex(item => item.a === curr.a);

  if (index === -1) acc.push(curr);

  return acc;

}, []);

console.log(uniqueArr);



This uses the reduce() method to iterate over the array and build a new array of unique objects, where uniqueness is determined by the a property. The findIndex() method is used to check if the current object already exists in the new array based on the value of its a property. If the current object does not exist in the new array, it is pushed to the array. The output will be an array of objects where each object is unique based on the a property:


[{a: 1, b: 'foo'}, {a: 2, b: 'bar'}, {a: 3, b: 'qux'}]




Comments

나의 재물운? 연애운은?

AI가 봐주는 내 사주팔자 - 운세박사

https://aifortunedoctor.com/

Category
Magazine
훈남/훈녀
 
 
 
상점
Facebook Twitter GooglePlus KakaoStory NaverBand