Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

JavaScript: Remove duplicate items from an array, ignore case sensitivity

JavaScript Array: Exercise-14 with Solution

Write a JavaScript program to remove duplicate items from an array (ignore case sensitivity).

Pictorial Presentation:

JavaScript: Remove duplicate items from an array, ignore case sensitivity

Sample Solution-1:

JavaScript Code:

function removeDuplicates(num) {
  var x,
      len=num.length,
      out=[],
      obj={};
 
  for (x=0; x<len; x++) {
    obj[num[x]]=0;
  }
  for (x in obj) {
    out.push(x);
  }
  return out;
}
var Mynum = [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6];
result = removeDuplicates(Mynum);
console.log(Mynum);
console.log(result);

Sample Output:

[1,2,2,4,5,4,7,8,7,3,6]
["1","2","3","4","5","6","7","8"]

Flowchart:

Flowchart: JavaScript: Display the colors entered in an array by a specific format

Sample Solution-2:

Removing duplicates from an array in JavaScript can be done in a variety of ways, such as using Array.prototype.reduce(), Array.prototype.filter() or even a simple for loop. But there's an easier alternative. JavaScript's built-in Set object is described as a collection of values, where each value may occur only once. A Set object is also iterable, making it easily convertible to an array using the spread (...) operator.

JavaScript Code:

//Source:https://bit.ly/3hEZdCl
//Remove duplicates from a JavaScript array
const nums = [1, 2, 2, 3, 1, 2, 4, 5, 4, 2, 6];
console.log([...new Set(nums)])

Sample Output:

[1,2,3,4,5,6]

Live Demo:

See the Pen JavaScript - Remove duplicate items from an array, ignore case sensitivity - array-ex- 14 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a JavaScript program to add items in an blank array and display the items.
Next: Write a JavaScript program to display the colors entered in an array by a specific format.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

How to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

Ref: https://bit.ly/2BXbp04