Given an array containing items (numbers and strings), remove all the duplicates.
- Set() – creating a set with an array automatically removes the duplicates
- array.filter() – filter out already existing values
// Remove duplicates from an array
const array = [1, 1, 2, 3, 4, "a", "a", "b"];
// Set automatically removes duplicates
const setArray = [...new Set(array)];
console.log("setArray", setArray);
// "setArray" [1,2,3,4,"a","b"]
// Filters and keeps only the first occuring value
const filteredArray = array.filter(
(item, index) => array.indexOf(item) === index
);
console.log("filteredArray", filteredArray);
// "filteredArray" [1,2,3,4,"a","b"]Code language: JavaScript (javascript)