Amrmsmb
Amrmsmb

Reputation: 11388

how tp prevent duplication in an array

As shown in the below posted code, the array arr wil contain obj.name and obj.text every time the function func is called. what at i want to know is, is there a recommended way in javascript to prevent the array from having the same obj.name and obj.text more than once?

note: the function func contains the object obj but actually it has more than two properties

please let me know the recommended way in javascript to prevent duplicate entries to the array code

  func(obj) {

  obj.name = name;
  obj.text = text;

  arr.push(obj);
  }

Upvotes: 0

Views: 87

Answers (3)

Air1
Air1

Reputation: 567

To avoid duplicate on name, use arr as an object (and yeah better change its name too ;) ) and use the name as a key :

func(obj) {
  obj.name = name;
  obj.text = text;
  arr[name] = obj;
}

If you want to avoid duplicates on name and text you could use the same idea :

func(obj) {
  obj.name = name;
  obj.text = text;
  arr[name] = arr[name] || {};
  arr[name][text] = obj;
}

Edit: in this case arr would be an object and not an array. You would be able to iterate through its properties with Object.keys

Upvotes: -2

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5041

May be in new answers you will get the best suggesstion, but what you can do is

  func(obj) {

     obj.name = name;
     obj.text = text;

     var index = arr.findIndex(item => item.name === obj.name);
     if (index !== -1) {
       arr.splice(index, 1);
     }
     arr.push(obj);
  }

Upvotes: 2

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You can check the object of the array that matches with the name and text of already existing object. You can use,

arr.find(item => item.name === obj.name && item.text === obj.text)

It will return a object if object with name and text value already exist in the arr array else undefined.

 func(obj) {

  obj.name = name;
  obj.text = text;
  var existingItem = arr.find(item => item.name === obj.name && item.text === obj.text);
    if(!existingItem){
      arr.push(obj);
    }
  }

Upvotes: 1

Related Questions