Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element from an array by field names

I have the next array:

0: {id: "10", tipo: "work"}
1: {id: "11", tipo: "work"}
2: {id: "24", tipo: "school"}
3: {id: "9", tipo: "work"}
4: {id: "25", tipo: "school"}

What I want to do is to remove an element from the array where two values match, for example, if id = 24 and tipo = school, the array at the position 2, must be removed, I have this function to find the array key by the values:

function eliminarElementoArray(array,val1,val2){   
     for (var i=0; i<array.length; i++){
       if (array[i].id == val1 && array[i].tipo == val2)                    
          return i;
       else
          return false;
     }
 } 

The function does not work correctly, in some cases it returns false, others, it returns an incorrect value.

Finally here is where the array values are removed, but it does not work because the previous function does not return the correct values:

selected.splice( eliminarElementoArray(selected, id, tipo), 1);

If someone can help me, I would be grateful.

like image 542
U.C Avatar asked Sep 19 '18 16:09

U.C


1 Answers

Problem :

The return false; statement inside for loop: The function will always check the first element of the array then if it does not match it will move to the else clause and return false without looping through the rest of the elements.

Solution :

You should move the return statement out of the loop so if no element of the array matches the passed arguments the function will return false.

NOTE: As @Taplar's comment says, It will be better to return a Truthy (no falsy) value like -1 for example since the splice() method will consider false as zero 0 and remove the first item.

function eliminarElementoArray(array, val1, val2) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id == val1 && array[i].tipo == val2)
      return i;
  }

  return -1;
}

var my_array = [{id: "10",tipo: "work"}, {id: "11",tipo: "work"}, {id: "24",tipo: "school"}, {id: "9",tipo: "work"}, {id: "25",tipo: "school"}];

console.log(eliminarElementoArray(my_array, "10", "work"));
console.log(eliminarElementoArray(my_array, "11", "fail test"));
console.log(eliminarElementoArray(my_array, "25", "school"));
like image 177
Zakaria Acharki Avatar answered Oct 03 '22 21:10

Zakaria Acharki