JavaScript

How to remove duplicates from an array using Javascript

You can use the forEach() method in combination with the Object.keys() method to remove duplicate values from an array or to get all unique values from an array in JavaScript. Here is an example:
 

How to remove duplicates from an array using Javascript
const colors = ["Blue", "Red", "Orange", "Green", "Blue"];

function removeDuplicates(colors) 
{
  //create new object wich will hold unique color
  let unique = {};
  
  colors.forEach(function(i) {
    if(!unique[i]) {
      unique[i] = true;
    }
  });
  
  return Object.keys(unique);
}

uniqueColors = removeDuplicates(colors);
console.log(uniqueColors);

Output:

["Blue", "Red", "Orange", "Green"]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *