简体   繁体   中英

Better way to find if item exists in JS array

I have and array which contains more then 10 000 values and somehow lodash method includes stopped working.

The example of array:

  ['888888111118888',
  '7771117717717771']

And my method (not working) but were working yesterday as well (with lower amount of values in array)

toFind = '7771117717717771'; // this is just for example
return _.includes(arr, toFind);

and no matter if the toFind is in array the method returns "false". Any suggestions?

EDIT

so this is what I have noticed now:

        console.log(data.memberList.members[0].steamID64[7]);
        toFind = data.memberList.members[0].steamID64[7];
        console.log(_.findIndex(data.memberList.members[0].steamID64, toFind));

and it responds with:

999999999999
-1

so how is this even possible?

Example of Array.prototype.findIndex:

let arr = [ "123", "456" ];
let index = arr.findIndex ( x => { return x === "123" } );

This will return 0 (the first index of "123"). If you have objects:

let arr = [ { val : "123" }, { val : "456" } ];
let index = arr.findIndex ( x => { return x.val === "123" } );

And so on. If you get -1, either your matcher is wrong, or it's not in the array.

I have tremendous respect for lodash, but as we get increasing native capability such as maps, sets, along with other functional higher order capabilities (filter, map, reduce, findIndex, etc), I've found my use of it diminishing.

Array.prototype.find

let result = arr.find(r => r ==='7771117717717771');

If result is defined then it exists in the array. If you are looking for an operation that runs faster than O(n) time, you should look into alternative data structures such as maps or trees

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM