0

I am creating a project using Angular. During the development, I am facing a problem when pushing values to my array. My requirement is that I want to push the value to the array unless the value already exists in the array. If it already exists, then simply replace that value with newer value.

This is my code, which is currently not working:

var obj = {
   question_id: "1",
   id: "2",
   "question": "This is a test"
};

This is the object that I want to push:

this.selectedOptions = [];

if (!this.selectedOptions.some(function(entry) { return entry.question_id === category.question_id;})) {
    this.selectedOptions.push(category);
}
3
  • What is this.selectedOptions? Add it to your question Commented Jul 29, 2020 at 15:30
  • @AnuragSrivastava: Added into the question Commented Jul 29, 2020 at 15:35
  • What information is given by this.selectedOptions = []? You need to post what the structure of objects inside that array is Commented Jul 29, 2020 at 15:37

4 Answers 4

2

Your code will push the item to the array, but it won't replace an existing item. I'm assuming that its an array of objects, given the entry.question_id part.

What you need is to check if the object exists in the array, and update or push it accordingly. The findIndex method will return the object index, if it exists in the array, or -1 if not.

const entryIndex = this.selectedOptions.findIndex(entry => entry.question_id === category.question_id);
if (entryIndex > -1) {
  this.selectedOptions[entryIndex] = category;
} else {
  this.selectedOptions.push(category);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could find the index for update or push something new.

let index = this.selectedOptions.findIndex(function (entry) {
    return entry.question_id === category.question_id;
});

if (index === -1) {
    this.selectedOptions.push(category);
} else {
    this.selectedOptions[index].someKey = 'someValue';
}

Comments

1

Try this:

function customUpsert(arr, data) {
   const index = arr.findIndex((e) => e.id === data.id);

   if (index === -1) {
      arr.push(data);
   } else {
      arr[index] = data;
   }
}

Comments

0

Following funcntion checks if "oldVal" exists and replace it with the "newVal" if it does.

var selectedOptions = [1, 2, 3];

function replaceOrAppend(oldVal, newVal) {

  let idx = selectedOptions.indexOf(oldVal);
  
  if (idx < 0)
    selectedOptions.push(newVal)
  else
    selectedOptions[idx] = newVal;
  

}


replaceOrAppend(1, 100);
replaceOrAppend(10, 200);

console.log(selectedOptions);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.