개발

객체 배열 중복 제거 (Map())/배열 중복 개수 출력(forEach)

카레공 2022. 5. 25. 10:49

 

 

 

 

인터넷에서 찾아본 방법은 아래와 같다

1. 배열 중복 개수 출력

const arr = ['a', 'b', 'a', 'b', 'c'];

const result = {};
arr.forEach((x) => { 
  result[x] = (result[x] || 0)+1; 
});


//쉽게 해석하자면

result[x] = (result[x] || 0) + 1;
// 이 코드를 좀 더 풀어쓰면 아래와 같다.
if(result[x]) {
  result[x] = result[x]+1;
} else {
  result[x] = 0 + 1;
}

2. 객체배열 중복 제거 데이터

function removeRpt(ObjArr) {
  const map = new Map();
  for (const character of ObjArr) {
    map.set(JSON.stringify(character), character);
  }
  const arrUnique = [...map.values()];
  console.log(arrUnique);

  return arrUnique;
}