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:
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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework