Remove Original And Duplicate From An Array Of Objects - Js
I have an array of objects. const arr = [   { title: 'sky', artist: 'Jon', id: 1 },   { title: 'rain', artist: 'Paul', id: 2 },   { title: 'sky', artist: 'Jon', id: 1 } ];  I would
Solution 1:
You could take an object and filter with the value of the hash table.
const
    array = [{ title: "sky", artist: "Jon", id: 1 }, { title: "rain", artist: "Paul", id: 2 }, { title: "sky", artist: "Jon", id: 1 }, { title: "rain", artist: "Paul", id: 2 }],
    ids = array.reduce((r, { id }) => (r[id] = !(id in r), r), {}),
    result = array.filter(({ id }) => ids[id]);
console.log(result);Solution 2:
That's a one-liner:
list.filter(el => list.filter(e => e.title == el.title).length == 1);
const arr = [{
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  },
  {
    title: "sky",
    artist: "Jon",
    id: 1
  }
];
const arr1 = [{
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  },
  {
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  }
];
functionremoveDupes(list) {
  return list.filter(el => list.filter(e => e.id == el.id).length == 1);
}
console.log(removeDupes(arr));
console.log(removeDupes(arr1));Solution 3:
One way to do it, in order to avoid running an exponential loop is to save all values to a new object, and convert that object to a new array.
const combinedObj = arr.reduce((obj, item) => { obj[item.id] = item; return obj; }, {});
const newArray = Object.values(combinedObj)
Solution 4:
you can do it in one line like this:
const res = arr.filter(elem => (arr.filter(obj => obj.id === elem.id)).length === 1)
or you can do it like this(better in terms of time complexity):
const arr = [
  { title: "sky", artist: "Jon", id: 1  },
  { title: "rain", artist: "Paul", id: 2  },
  { title: "sky", artist: "Jon", id: 1  },
];
const counts = arr.reduce((counts, curr) => (counts[curr.id] = ++counts[curr.id] || 1, counts), {})
const res = arr.filter(curr => counts[curr.id] === 1)
Solution 5:
You could run the array through reduce() and then use some to see if you should add if it does not exist, or remove using filter if it does.
Snippet:
const arr = [
  { title: "sky", artist: "Jon", id: 1  },
  { title: "rain", artist: "Paul", id: 2  },
  { title: "sky", artist: "Jon", id: 1  },
  { title: "rain", artist: "Paul", id: 2  },
  { title: "earth", artist: "Frank", id: 3  },
];
const unique = arr.reduce((accumulator, currentValue) => { 
  // add if we don't haveif (!accumulator.some(x => x.id === currentValue.id)) {
    accumulator.push(currentValue);
  } else {
    // remove if we do
    accumulator = accumulator.filter(x => x.id !== currentValue.id);
  }
  
  return accumulator;
}, []); 
console.info(unique);
Post a Comment for "Remove Original And Duplicate From An Array Of Objects - Js"