-2

How to remove duplicated values in this object array in javascript?

0: {d: “2021/01/19”, color: “#009988"}
1: {d: “2021/01/19”, color: “#CC3311"}
2: {d: “2021/01/19”, color: “#009988"}
3: {d: “2021/01/19”, color: “#009988"}
4: {d: “2021/01/20”, color: “#009988"}
5: {d: “2021/01/22”, color: “#009988"}

I want to filter this object array like this:

0: {d: “2021/01/19”, color: “#009988"}
1: {d: “2021/01/19”, color: “#CC3311"}
2: {d: “2021/01/20”, color: “#009988"}
3: {d: “2021/01/22”, color: “#009988"}

I have done this way, but the result was not what I wanted.

    for (let i = 0; i < array.length-1; i++) {
      if (arr[i].d === array[i+1].d) {
        if (array[i].color === array[i+1].color) {
          array.splice(i, 1);
          i--;
        }
      }
    }
Hyewon Joo
  • 13
  • 1
  • 6

3 Answers3

0
arr.filter((el, index) => arr.findIndex(t => t.d === el.d && t.color === el.color) === index)
Baiwei
  • 235
  • 2
  • 7
0
const initArray = [
  { d: "2021/01/19", color: "#009988"},
  { d: "2021/01/19", color: "#CC3311"},
  { d: "2021/01/19", color: "#009988"},
  { d: "2021/01/19", color: "#009988"},
  { d: "2021/01/20", color: "#009988"},
  { d: "2021/01/22", color: "#009988"}
];

const result = [];

initArray.forEach((itm) => {
  if (!(result.some(item => item.d === itm.d && item.color === itm.color))) {
    result.push(itm)
  }
});
Knyazik01
  • 61
  • 4
0

const input=[{d:"2021/01/19",color:"#009988"},{d:"2021/01/19",color:"#CC3311"},{d:"2021/01/19",color:"#009988"},{d:"2021/01/19",color:"#009988"},{d:"2021/01/20",color:"#009988"},{d:"2021/01/22",color:"#009988"}];

const res = input.filter((e,i,a) => 
  a.findIndex(x => x.d === e.d && x.color === e.color) === i
)

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */
ulou
  • 5,542
  • 5
  • 37
  • 47