-1

Js Object, ReactJs

{userId:1, userName:mahadi}, 
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]
Gandalf the White
  • 2,415
  • 2
  • 18
  • 39

2 Answers2

0

there can be multiple solution to this particular problem. But here is simplified solution using reduce and some methods available in Prototype of Array.

const arr = [{userId:1, userName:"mahadi"}, 
             {userId:2,userName:"hasan"},
             {userId:1, userName:"mahadi"}
            ]


const reducedArr = arr.reduce((accumulator, currentValue) =>{
   //check if your accumulator already does not includes an object with same username 
    if(!accumulator.some(single => single.userName === currentValue.userName) ){
          return [...accumulator, currentValue]
      }
     return accumulator

//initialize accumulator here
  }, [])



 console.log(reducedArr)
Afraz Ahmad
  • 386
  • 1
  • 5
  • 20
0

const origin = [{
    userId: 1,
    userName: "mahadi"
  },
  {
    userId: 2,
    userName: "hasan"
  },
  {
    userId: 1,
    userName: "mahadi"
  }
];

const result = origin.filter(function(element, index, arr) {
  return index === arr.findIndex(e => e.userId == element.userId);
});

const repeat = origin.filter(function(element, index, arr) {
  return index !== arr.findIndex(e => e.userId == element.userId);
});

console.log("result", result);
console.log("repeat", repeat);
Ian
  • 1,198
  • 1
  • 5
  • 15