'Return array of objects with respect to uniqueness of property: Javascript
I am having array of objects with the following structure
const arr = [
{id: 0, name: "abc", userid: "0"},
{id: 1, name: "lmn", userid: "123"},
{id: 3, name: "pqr", userid:"456"},
{id: 4, name: "xyz", userid: "123"}
]
I want to return the objects where userid should be unique and is not equals to "0".
This is my approach. It returns just everything
const result = [
...new Set(
arr.map((node) => {
if (node.userid !== "0") return node;
})
)
];
console.log(result);
Solution 1:[1]
Maybe that might me done in a more short-hand way, but it works this way:
const arr = [
{id: 0, name: "abc", userid: "0"},
{id: 1, name: "lmn", userid: "123"},
{id: 3, name: "pqr", userid: "456"},
{id: 4, name: "xyz", userid: "123"}
];
const clearZero = arr.filter((obj) => obj.id != 0);
const finalArray = [];
clearZero.forEach((obj) => {
if (finalArray.every((elem) => elem.userid !== obj.userid)) {
finalArray.push(obj);
}
})
console.log(finalArray); // logs out no. 1 and no.3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kacper ?uczak |
