Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Only One Duplicate from An Array

Tags:

javascript

I'm trying to only remove one of the 2s from an array, but my code removes all of them. My code is as follows:

var arr = [2,7,9,5,2]
arr.filter(item => ((item !== 2)));

and:

var arr = [2,7,9,2,2,5,2]
arr.filter(item => ((item !== 2)));

Both remove all the 2s. I thought about removing duplicates, where it works if there's only one duplicate - e.g.:

Array.from(new Set([2,7,9,5,2]));
function uniq(a) {
 return Array.from(new Set(a)) 
}

But fails if there's multiple duplicates as it just removes them all, including any other duplicated numbers:

Array.from(new Set([2,7,9,9,2,2,5,2]));
function uniq(a) {
 return Array.from(new Set(a)) 
}

Does anyone know how to only remove one of the 2s? Thanks for any help here.

like image 690
user8758206 Avatar asked Apr 15 '26 10:04

user8758206


2 Answers

You could use indexOf method in combination with splice.

var arr = [2,7,9,5,2]
var idx = arr.indexOf(2)
if (idx >= 0) {
    arr.splice(idx, 1);
}
console.log(arr);
like image 165
Mihai Alexandru-Ionut Avatar answered Apr 16 '26 23:04

Mihai Alexandru-Ionut


You could take a closure with a counter and remove only the first 2.

var array = [2, 7, 9, 2, 3, 2, 5, 2],
    result = array.filter((i => v => v !== 2 || --i)(1));
    
console.log(result);

For any other 2, you could adjust the start value for decrementing.

var array = [2, 7, 9, 2, 3, 2, 5, 2],
    result = array.filter((i => v => v !== 2 || --i)(2));
    
console.log(result);
like image 37
Nina Scholz Avatar answered Apr 16 '26 22:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!