Skip to content
Advertisement

Javascript findIndex is not a function

I have a json array:

[    
  {"id":19,"name":"Jed", "lastname":"DIAZ", "hobby":"photo", "birthday":"2011/11/22"},
  {"id":20,"name":"Judith", "lastname":"HENDERSON", "hobby":"pets", "birthday":"1974/06/12"},
  {"id":21,"name":"Nicolai", "lastname":"GRAHAM", "hobby":"reading", "birthday":"2005/01/22"},
  {"id":22,"name":"Vasile", "lastname":"BRYANT", "hobby":"singing", "birthday":"1987/03/17"}
]

function to remove a item from json array

 removeItem: function(removeId){
   //paramater validation
   return dataLoad.then(function(data){

     f = data.findIndex(function(item) { return item.id == removeId; });

     if(f < 0)
       return false;
     data.splice(f,1);

     LS.setData(data,"cutomers");

     return true;
   });
 }

When the code is running there is an error:

findIndex is not a function

error line

 f = data.findIndex(function(item) { return item.id == removeId; });

Advertisement

Answer

findIndex is not a prototype method of Array in ECMASCRIPT 262, you might need filter combined with indexOf, instead, it has the advantage of stopping searching as soon as entry is found

var f;
var filteredElements = data.filter(function(item, index) { f = index; return item.id == removeId; });


if (!filteredElements.length) {
    return false;
}

data.splice(f, 1);

EDIT as suggested in comments by Nina Scholz:

This solution is using Array.prototype.some instead

var f;
var found = data.some(function(item, index) { f = index; return item.id == removeId; });

if (!found) {
    return false;
}

data.splice(f, 1);

Found at Array.prototype.findIndex MDN

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement