Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to remove only one value from duplicate array values

I have an array ['2530491','2530491','2530491','2530492'] the 2530491 is duplicated thrice, and I want to remove a single value of 2530491 from 3 of them, so the output would be like : ['2530491','2530491','2530492'].

fileArrayAnnounce_size = jQuery.grep(fileArrayAnnounce_size, function(value){
  return value != file_size.metas[0].size;
});

I try grip but it removes all value which same. I want to remove only a single value from duplicates.

like image 429
HiFlyer Ojt Avatar asked Oct 24 '25 17:10

HiFlyer Ojt


1 Answers

You can use splice and indexOf to remove the first instance:

fileArrayAnnounce_size.splice(fileArrayAnnounce_size.indexOf('2530491'), 1)

A safer way:

var index = fileArrayAnnounce_size.indexOf('2530491')
if (index > -1) {
    fileArrayAnnounce_size.splice(index, 1);
}

Check and remove duplicates:

var mapOfValues = fileArrayAnnounce_size.reduce(function(vals, current) {
    if (vals[current]) {
        vals[current]++;
    } else {
        vals[current] = 1;
    }

    return vals;
}, {});

And now check and remove anything with more than 1 value:

for (var value in mapOfValues) {
    if (mapOfValues[value] > 1) {
        var idx = fileArrayAnnounce_size.indexOf(value);
        fileArrayAnnounce_size.splice(idx, 1);
    }
}

Demo: https://jsfiddle.net/1277mxt9/

like image 123
tymeJV Avatar answered Oct 26 '25 08:10

tymeJV



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!