Array or object : how to choose

… nail or screw ?


Here is how I choose :

  • Array are not associative in javascript.

Array have some facility function (indexOf, foreEach, etc)
Note: bonus there is pretty always a Polyfill for them (so don’t hesitate to use them in any browser)

  • Object can be used as associative array.

And Object can have function (methods), and constructor (sort of : using function constructor)
→ Object is more versatile than array

  • and at least : Arrays have order, objects don’t

Conclusion :

Use array if you need ordered values, or want to use a function facilities below, otherwise use object

Array function facilities

  • .map() returns a new Array of objects created by taking some action on the original item.
  • .every() returns a boolean - true if every element in this array satisfies the provided testing function. An important difference with .every() is that the test function may not always be called for every element in the array. Once the testing function returns false for any element, no more array elements are iterated. Therefore, the testing function should usually have no side effects.
  • .forEach() returns nothing - It iterates the Array performing a given action for each item in the Array.
  • .some() stops looping the first time the iterator returns true or something truthy.
  • .filter() creates a new array including elements where the filter function returns true and omitting the ones where it returns false
  • .reduce() (builds up a value by repeated calling the iterator, passing in previous values; see the spec for the details; useful for summing the contents of an array and many other things)
  • .reduceRigth() (like reduce, but works in descending rather than ascending order)

More explanations at :

Array tips : remove an element from array

Remove one element from array : using splice method

var array = [2, 5, 9];

// We want to remove the 5 : first find his index
var index = array.indexOf(5);

// Check index is valid and splice :
if (index > -1) {
  array.splice(index, 1); // the 2nd parameter is how many element to remove