3

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!

2
  • 1
    "What's the best way to do this?" Ah, the age old question on SO. Commented Feb 20, 2017 at 14:39
  • What if the collection contains 3 duplicate keys? Then do you want the last? Commented Feb 20, 2017 at 14:43

5 Answers 5

4

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);

Sign up to request clarification or add additional context in comments.

4 Comments

Not the output user expects!
@ibrahimmahrir He asked what's the best way to do it.. Meaning he would like to see additional approaches..
This is perfect. Nicely done. Solves my problem, thank you!
Sure thing.. Glad I could help :)
0

You can use a hash object to get the key-value pairs without duplicates and then transform the hash object back into an array like this:

function removeDuplicates(arr) {
  var hash = arr.reduce(function(h, e) {
    var parts = e.split("=");
    h[parts[0]] = parts[1];
    return h;
  }, {});
  
  return Object.keys(hash).map(function(key) {
    return key + "=" + hash[key];
  });
}

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

console.log(removeDuplicates(user_filters));

Comments

0

You could use a Map which does the unique/overriding automatically, and is able to get you an array back in case you need it

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

var m = new Map(user_filters.map(v => v.split("=")));
console.log([...m.entries()].map(v => v.join("="))); 

1 Comment

Not the output user expects!
0

It would be better to iterate from back of array , thus for every unique key you need to keep a variable true or false (initially false). so if true mean already occurred so deleted it else keep it and make its variable true .

It is much more better approach then your current . you don't have to keep last index and swapping then deleting.

Comments

0

You may convert to json and then back to the array format you want . IN the below code you get the result object in the format you want.

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

function toJson(obj){
var output = {};
$.each(obj, function(i){
    var keyvalPair = this.split('=')
  var key = keyvalPair[0];
  output[key]= keyvalPair[1];
});
return output;
}
function toArray(obj){
var output = [];
$.each(obj, function(i){
    output.push(i+"="+obj[i]);
});
return output;
 }
var result = toArray(toJson(user_filters));
 console.log(result); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.