Problem
You want to remove duplicates from arrays.
Ingredients
- two for loops
- the
concatmethod - the
splicemethod
Directions
-
Given: an array with duplicate values.
let array = ['John', 'James', 'John', 'Jane', 'John']; let result = removeDuplicates(array); console.log(result); // expected content of array3: ['John', 'James', 'Jane'] -
Create the
removeDuplicatesfunction and inside create a copy of thearrayparameter (e.g., by using theconcat()method).function removeDuplicates(array) { let result = array.concat(); ... return result; } -
Iterate over each element in the copy.
function removeDuplicates(array) { let result = array.concat(); for(let i=0; i<result.length; ++i) { ... } return result; } -
For each element iterate over all the other elements.
function removeDuplicates(array) { let result = array.concat(); for(let i=0; i<result.length; ++i) { for(let j=i+1; j<result.length; ++j) { ... } } return result; } -
Compare the element with each other element.
function removeDuplicates(array) { let result = array.concat(); for(let i=0; i<result.length; ++i) { for(let j=i+1; j<result.length; ++j) { if(result[i] === result[j]) { ... } } } return result; } -
If both elements are equal (
===) then delete the duplicate using thesplice()method.function removeDuplicates(array) { let result = array.concat(); for(let i=0; i<result.length; ++i) { for(let j=i+1; j<result.length; ++j) { if(result[i] === result[j]) { result.splice(j--, 1); } } } return result; } -
Voilá, there you got a function which removes duplicates from an array.
let array = ['John', 'James', 'John', 'Jane', 'John']; let result = removeDuplicates(array); console.log(result); // ['John', 'James', 'Jane']
Notes
- This recipe only works for strict equality (
===), not for logical equality (e.g., it doesn’t work for different objects containing the same information). - This recipe has O(n2) runtime.
Alternative recipes
-
Since ES2015: use the
Setdatatype which doesn’t allow duplicates by default.function removeDuplicates(...array) { return [...new Set([].concat(...array))]; }