1

I want to check if the an id already exist in my array. if It exists the older value should be removed, and the new value should be added to the array, if not it should be added to the array.

Here's the code that I tried but didn't work.

sample_array[0] = {'id' : 1, 'letter': 'a'};
sample_array[1] = {'id' : 2, 'letter': 'b'};
sample_array[2] = {'id' : 3, 'letter': 'c'};
sample_array[3] = {'id' : 4, 'letter': 'd'};
sample_array[4] = {'id' : 5, 'letter': 'e'};

input_id = 3;
count_length = sample_array.length;
input_letter = 'L'; 
idx = $.inArray(input_id, sample_array.id); // <- i think this is where it goes wrong.

if(idx ==  -1)
{
   //add to the array
   sample_array[count_length] = {'id' : input_id, 'letter': input_letter};              
}
else
{
   //remove then add to the array
   sample_array.splice(idx, 1);
   sample_array[count_length] = {'id' : input_id, 'letter': input_letter}; 
}
KennethC
  • 746
  • 2
  • 10
  • 27
  • follow this : http://stackoverflow.com/questions/21809116/how-to-use-php-in-array-with-associative-array I hope it will help you. – Sonu Sindhu Mar 09 '16 at 12:43
  • Possible duplicate of [Why jQuery.inArray doesn't work on array of objects](http://stackoverflow.com/questions/19111707/why-jquery-inarray-doesnt-work-on-array-of-objects) – ozil Mar 09 '16 at 13:00

1 Answers1

1

You are searching for a primitive value not an object, so

replace from this line onwards

idx = $.inArray(input_id, sample_array.id);

with

sample_array.forEach(function(value,index){
   if(value.id==input_id)
   {
     sample_array.splice(index,1);
   }
}).length;
sample_array.push({'id' : input_id, 'letter': input_letter});
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • I removed the .length because I get an error of an undefined array length. It works fine, bro thanks. I really hate arrays in javascript. haha – KennethC Mar 09 '16 at 13:01