Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript findIndex is not a function

Tags:

javascript

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; });
like image 822
Gigi Avatar asked Aug 26 '15 08:08

Gigi


1 Answers

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

like image 101
axelduch Avatar answered Oct 04 '22 03:10

axelduch