Home > Net >  Remove first occurence of an element using JavaScript or Lodash
Remove first occurence of an element using JavaScript or Lodash

Time:01-21

I have an array like this -

["a", "a", "b", "c", "d", "e"]

I want to operate on this and filter it to remove only the first occurence of every element in the array.

The output in the above case is expected to be - ["a"]

How can I achieve this using JavaScript or Lodash?

CodePudding user response:

By wanting the first one of duplicate following items, you could use Array#lastIndexOf along with a check of the actual index.

const
    data = ["a", "a", "b", "c", "d", "e"],
    result = data.filter((v, i, a) => i !== a.lastIndexOf(v));

console.log(result);

CodePudding user response:

You can use an empty object as a map to easily check if the item has been found before and then use Array#filter to remove the ones you don't want.

var list = ["a", "a", "b", "c", "d", "e"];
var occurences = {};
var filteredList = list.filter(function(item) {
  if (item in occurences) return true; // if it has already been registered, add it to the new list
  occurences[item] = 1; // register the item
  return false; // ignore it on the new list
});
console.log(filteredList);

Shorthand version

let list = ["a", "a", "b", "c", "d", "e"], occurences = {};
list = list.filter(item => item in occurences ? 1 : occurences[item] = 1 && 0);
console.log(list);

CodePudding user response:

you can simply use shift method checkout it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

  •  Tags:  
  • Related