Top arrays Questions

List of Tags
620
brad

What is the most concise and efficient way to find out if a JavaScript array contains an obj?

This is the only way I know to do it:

contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

Answered By: codeape ( 1021)

Modern browsers have Array#indexOf, which does exactly that; this is in the new(ish) ECMAScript 5th edition specification, but it has been in several browsers for years. Older browsers can be supported using the code listed in the "compatibility" section at the bottom of that page.

jQuery has a utility function for this:

$.inArray(value, array)

It returns the index of a value in an array. It returns -1 if the array does not contain the value.

jQuery has several useful utility functions.

An excellent JavaScript utility library is underscore.js:

Some other frameworks:

Notice how some frameworks implement this as a function. While other frameworks add the function to the array prototype.

Languages that compile to javascript

In coffeescript, the in operator is the equivalent of contains:

a = [1, 2, 3, 4]
alert(2 in a)

Dart:

var mylist = [1, 2, 3];
assert(mylist.contains(1));
assert(mylist.indexOf(1) == 0);
454
Ron Tuffin

I have an array that is initialised like:

Element[] array = {new Element(1),new Element(2),new Element(3)};

I would like to convert this array into an object of the ArrayList class.

ArrayList<Element> arraylist = ???;

I am sure I have done this before, but the solution is sitting just at the edge of my memory.

Answered By: Tom ( 564)
new ArrayList<Element>(Arrays.asList(array))

As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]

Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a] ?

Edit: The accepted answer is great. For a lower level view of how this works, see the comments section on that answer. There's a phenomenal conversation there about it. (This edit written about the comments available at the time. ie: the first ~16)

Answered By: Mehrdad Afshari ( 582)

Because a[5] will evaluate to:

*(a + 5)

and 5[a] will evaluate to:

*(5 + a)

and from elementary school math we know those are equal.

This is the direct artifact of arrays behaving as pointers, "a" is a memory address. "a[5]" is the value that's 5 elements further from "a". The address of this element is "a + 5". This is equal to offset "a" from "5" elements at the beginning of the address space (5 + a).

379
interstar

How do I append to an array in Javascript?

Answered By: jdecuyper ( 489)

Use the push() function to append to an array:

// initialize array
var arr = new Array(3); // Optional count -- it controls the array's size
arr[0] = "Hi";
arr[1] = "Hello";
arr[2] = "Bonjour";

// append new value to the array
arr.push("Hola");

// display all values
for (var i = 0; i < arr.length; i++) {
    alert(arr[i]);
};

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method? For example:

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

Why even have the splice method if I can delete array elements like I can with objects?

Answered By: Andy Hume ( 554)

Delete won't remove the element from the array it will only set the element as undefined.

So,

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray
  [undefined, "b", "c", "d"]
> myArray.splice(0, 2)
  [undefined, "b"]
> myArray
  ["c", "d"]

How do I check if a particular key exists in a Javascript associative array?

If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Answered By: Ates Goral ( 461)

Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

You should instead use the in operator:

"key" in obj // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj   // ERROR!  Equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

obj.hasOwnProperty("key") // true
307
Darryl Hein

What is the best method for adding options to a select from a JSON object using jQuery?

I'm looking for something that I don't need a plugin to do, but would also be interested in the plugins that are out there.

This is what I did:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
  }
}

A clean/simple solution:

This is a cleaned up and simplified version of matdumsa's:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
          .append($('<option>', { value : key })
          .text(value)); 
});

Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

Answered By: matdumsa ( 350)

Same as other answers, in jQuery fashion:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
});
288
Gareth Simpson

If I have a javascript associative array say:

var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;

Is there a built in or accepted best practice way to get the length of this array?

EDIT: JavaScript does not have associative arrays -- it only has objects.

Answered By: James Coglan ( 392)

The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an object
var size = Object.size(myArray);

There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.

288
Antti Syk&#228;ri

I need to concatenate two String arrays in Java.

void f(String[] first, String[] second) {
    String[] both = ???
}

What is the easiest way to do this?

Answered By: Antti Syk&#228;ri ( 264)

I found a one-line solution from the good old Apache Commons Lang library. ArrayUtils.addAll(T[], T...). Code:

String[] both = ArrayUtils.addAll(first, second);
285
Mike Sickler

I have a String[] with values like so:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

Given String s, is there a good way of testing whether VALUES contains s?

Answered By: camickr ( 383)
Arrays.asList(...).contains(...)