Suppose I have a list of objects like this:
let b = [ { name: "test1", connectedTo: "", }, { name: "test1", connectedTo: "test1.test2.test3" }, { name: "test2", connectedTo: "", }, { name: "test3", connectedTo: "", } ]
I want to get elements without duplicates name
and also if there are duplicates take one without empty connectedTo
. So from example above the result that I expect is:
let result = [ { name: "test1", connectedTo: "test1.test2.test3" }, { name: "test2", connectedTo: "", }, { name: "test3", connectedTo: "", } ]
Advertisement
Answer
Here’s an approach utilizing Array#reduce
function:
let b = [ { name: "test1", connectedTo: "", }, { name: "test1", connectedTo: "test1.test2.test3" }, { name: "test2", connectedTo: "", }, { name: "test3", connectedTo: "test1.test2", }, { name: "test3", connectedTo: "", } ]; const result = Object.values(b.reduce((acc, cur) => { if(!acc[cur.name] || !acc[cur.name].connectedTo) acc[cur.name] = cur; return acc; }, {})); console.log(result);