Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove partial duplicate values in jquery array

I have a single level array of key/value pairs, like this:

var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square']

I need a function to perform the following:

  1. find all duplicate keys
  2. replace the first occurrence of the key/value pair with the second occurrence
  3. delete the second occurrence

In this case, it would produce the following result:

user_filters= ['color=blue', 'size=large', 'shape=square']

Something like...

function update_array(){
   $.each(user_filters, function(i){
      var key = this.split('=')[0];
      if(key is second occurrence in user_filters)
      {
          var index = index of first occurrence of key
          user_filters[index] = user_filters[i];
          user_filters.splice(i,1); 
      }

   });
}

What is the best way to do this? Thanks!

like image 401
p1xelarchitect Avatar asked Aug 05 '26 04:08

p1xelarchitect


1 Answers

I would keep the data in an object and this way any duplicate will automatically overwrite the previous entry..

See this for example:

var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var object = {};

for (var i = 0; i < user_filters.length; i++) {
  var currentItem = user_filters[i].split('=');
  var key = currentItem[0];
  var value = currentItem[1];
  object[key] = value;
}

console.log(object);
like image 110
Z-Bone Avatar answered Aug 06 '26 17:08

Z-Bone



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!