Best Way to Find If an Item Is in a JavaScript Array

Best way to find if an item is in a JavaScript array?

As of ECMAScript 2016 you can use includes()

arr.includes(obj);

If you want to support IE or other older browsers:

function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}

EDIT:
This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

       if (!Array.prototype.indexOf)
    {

    Array.prototype.indexOf = function(searchElement /*, fromIndex */)

    {

    "use strict";

    if (this === void 0 || this === null)
    throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
    return -1;

    var n = 0;
    if (arguments.length > 0)
    {
    n = Number(arguments[1]);
    if (n !== n)
    n = 0;
    else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
    n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
    return -1;

    var k = n >= 0
    ? n
    : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
    if (k in t && t[k] === searchElement)
    return k;
    }
    return -1;
    };

    }
  2. Daniel James's version:

     if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
    fromIndex = 0;
    } else if (fromIndex < 0) {
    fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var i = fromIndex, j = this.length; i < j; i++) {
    if (this[i] === obj)
    return i;
    }
    return -1;
    };
    }
  3. roosteronacid's version:

     Array.prototype.hasObject = (
    !Array.indexOf ? function (o)
    {
    var l = this.length + 1;
    while (l -= 1)
    {
    if (this[l - 1] === o)
    {
    return true;
    }
    }
    return false;
    } : function (o)
    {
    return (this.indexOf(o) !== -1);
    }
    );

How to determine if object is in array

Use something like this:

function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}

return false;
}

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}

return false;
}

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

How do I check if an array includes a value in JavaScript?

Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

Check if object value exists within a Javascript array of objects and if not add a new object to array

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];

function add(arr, name) {

const { length } = arr;

const id = length + 1;

const found = arr.some(el => el.username === name);

if (!found) arr.push({ id, username: name });

return arr;

}

console.log(add(arr, 'ted'));

Check if an element is present in an array

ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

Find a value in an array of objects in Javascript

You can loop over the array and test for that property:

function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}

var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);

How to determine if Javascript array contains an object with an attribute that equals a given value?

2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.

There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.

var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}

JavaScript: Best way to find if a value is inside an object in an array

found_flag = false;
for (i = 0; i < arr.length; i++) {
if (arr[i].color == 'blue') {
found_flag = true;
break;
}
}
if (found_flag === true)
{
alert(i);
} else {
alert('not found');
}


Related Topics



Leave a reply



Submit