2

What is the equivalents of php functions push_array and in_array in javascript?

Arrays are simple (not multidimensional).

Haven't found something native.

James
  • 42,081
  • 53
  • 136
  • 161

3 Answers3

4

You're looking for the push method and the indexOf method.

Note that indexOf is not supported by IE, so you'll need to implement it yourself, like this:

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) // shortcut for verifying if it's NaN
        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;
  };
}

(copied from MDC)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

push_array:

This is native to the Array object in JavaScript:

var someArray = [];
someArray.push(value);

in_array:

This is not native to the Array in JavaScript however some browsers have support for Array.indexOf which can be compared to -1. If that is not supported than you need to iterate over the items.

function inArray(elem, array) {
    if (array.indexOf) {
        return array.indexOf(elem) > -1;
    }

    for (var i = 0, length = array.length; i < length; i++) {
        if (array[ i ] === elem ) {
            return true;
        }
    }

    return false;
}
Adam Ayres
  • 8,732
  • 1
  • 32
  • 25
1

You have to be using the JavaScript Array object. Then you can use .push().

For find: How do I check if an array includes an object in JavaScript?

Community
  • 1
  • 1
Macy Abbey
  • 3,877
  • 1
  • 20
  • 30