HiFlyer Ojt
HiFlyer Ojt

Reputation: 31

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.

Upvotes: 4

Views: 3602

Answers (3)

kind user
kind user

Reputation: 41913

You could check if given element has dupe elements or not, if so - remove just one duplicate entry of specified element from the original array.

var arr = ['2530491','2530491','2530491','2530492'],
    hash = [...new Set(arr)];
    hash.forEach((v,i) => arr.indexOf(v) != arr.lastIndexOf(v) ? arr.splice(arr.indexOf(v), 1) : null);
    
    console.log(arr);

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122155

You can use filter() and pass one object as thisArg parameter to use it as hash table.

var data = ['2530491','2530491','2530491','2530492', '2530492'];

var result = data.filter(function(e) {
  if(!this[e]) this[e] = 1
  else if (this[e] == 1) return this[e] = 2, false
  return true;
}, {})

console.log(result)

Upvotes: 1

tymeJV
tymeJV

Reputation: 104805

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/

Upvotes: 5

Related Questions