Js Object, ReactJs
{userId:1, userName:mahadi},
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]
Js Object, ReactJs
{userId:1, userName:mahadi},
{userId:2,userName:hasan},
{userId:1, userName:mahadi}
]
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)
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);