Remove duplicate from array

Viewed 248

I want to remove each copy of object from array:

  const object = [
    { label: "SUA", value: "sua" },
    { label: "SUA", value: "sua" },
    { label: "Florida", value: "florida" }
  ];
  console.log(object.map(i=> [...new Set(i)]))

At the end i have to get like:

const object = [
    { label: "Florida", value: "florida" }
  ];

How to do this in my code?

5 Answers

You can use 2 for loops to achieve your functionality.

let result = [];
for(let i=0;i<object.length ;i++) {
    let isDuplicate = false;
    for(let j=0; j<object.length;j++) {
        if(object[i].label === object[j].label && object[i].value === object[j].value && i !== j) {
            isDuplicate = true;   
        }
    }
    if(!isDuplicate) result.push(object[i]);
}

Regardless of how many copies of each element you'd like to keep in the array, create a Map by definition Map<Location, number> and tabulate the number of occurrences of each Location object. Afterwards, take each element and append it to an array only once.


type Location = {label: string, value: string};

const object: Location[] = [
    { label: "SUA", value: "sua" },
    { label: "SUA", value: "sua" },
    { label: "Florida", value: "florida" }
];
const objects: Map<Location, number> = new Map();

for (const location of object)
    if (objects.has(location))
        objects.set(location, objects.get(location) + 1);
    else
        objects.set(location, 1);

const filtered: Location[] = [];

for (const location of objects)
    if (location[1] === 1) // You change 1 to any value depending on how many copies of each you'd like.
        filtered.push(location[0];

Note This is TypeScript for clarity, but the concept is the same.

Short way:

const object = [
  { label: "SUA", value: "sua" },
  { label: "SUA", value: "sua" },
  { label: "Florida", value: "florida" }
];

const a = object.filter((v, i, a) => a.findIndex(t => (t.label === 
v.label && t.value === v.value)) === i);

console.log(a);

You can use ES6 set -

const unique = [...new Set(object.map(({value}) => value))].map(e => object.find(({value}) => value == e));

console.log("unique",unique);

//[{label: "SUA", value: "sua"},{label: "Florida", value: "florida"}]

for your problem you can simply use reduce -

const uniq =  object.reduce((a,b)=>{return a.value === b.value ? {} :[b]},[])

console.log(uniq);

//[{label: "Florida", value: "florida"}]

Simple solution with lodash

const object = [
    { label: "SUA", value: "sua" },
    { label: "SUA", value: "sua" },
    { label: "Florida", value: "florida" }
  ];

result = _.xor(_.uniqWith(object,_.isEqual),object)
Related