Questions tagged [arrays]

An array is an ordered linear data structure consisting of a collection of elements (values, variables, or references), each identified by one or more indexes. When asking about specific variants of arrays, use these related tags instead: [vector], [arraylist], [matrix]. When using this tag, in a question that is specific to a programming language, tag the question with the programming language being used.

An array is an ordered linear data structure consisting of a collection of elements (values or variables), each identified by at least one index, stored in contiguous memory locations.

An array is typically stored so that the position of each element can be computed from its index tuple by a mathematical formula.

In some languages (C, Java, etc.) the length of the array must be set beforehand. In other languages (Ruby, Python, LISP, Haxe, etc.) the length of the array grows dynamically as elements are added.

When tagging a question with this tag, also tag the question with the programming language being used.

Array in specific languages

  • C# arrays are actually objects and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members of the Array base type.
  • C arrays act to store related data under a single variable name with an index, also known as a subscript. They are stored in row-major order, which means the last subscript varies fastest. It is easiest to think of an array as simply a list or ordered grouping for variables of the same type. As such, arrays often help a programmer organize collections of data efficiently and intuitively.
  • C++ inherits raw arrays from C and adds its own array-class std::array for compile-time array sizes, std::vector for runtime dynamic sized arrays. It also has smart pointer implementations like std::unique_ptr, std::shared_ptr.
  • Objective C inherits raw arrays from C and adds its own array-class NSArray and NSMutableArray for dynamic arrays.
  • Ruby's normal array class is called array.
  • In Python, the normal array datatype is called a list, while the array type is used for homogeneous arrays.
  • In NumPy there is a powerful N-dimensional array with many capabilities.
  • PHP arrays are implemented as ordered maps which may contain a mix of numeric or string keys.
  • JavaScript arrays are just objects with a different prototype (with additional functions more useful for array-like structures), with numerical index values stored as strings (all JavaScript keys are strings). Unlike other objects, you cannot use dot notation to access keys - only square bracket notation.
  • In Haxe, an Array has one type parameter which corresponds to the type of collection of elements. Arrays can be created using their constructor new Array() or [1, 2, 3], but also using Array comprehension: [for (i in 0...10) if (i % 2 == 0) i]. For storage of fixed size the abstract type haxe.ds.Vector can be used, which may be faster than Array on some targets and is never slower.
  • In Scala, the normal array class is called Array. To get an element from an array you use parentheses (most languages use square brackets).
  • In Java, an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
  • In Perl, array variables are denoted with the @ prefix and arrays are declared with parentheses. Replacing the prefix with $# returns the last index.
  • In Rust, arrays are groups of data of the same type that are contiguous in memory, so they can be used when communicating with C. The length of an array is fixed.
  • In Swift, an array that includes the specified values, automatically inferring the array’s Element type. Swift makes it easy to create arrays in your code using an array literal: simply surround a comma-separated list of values with square brackets.
  • In Pascal, arrays declarations specify the index range rather than the number of elements; so parray: array [1..25] of real; declares a one-based array of 25 real numbers (valid elements are parray[1] thru parray[25]), whereas parray: array [0..24] of real; declares a zero-based ('C-style') array of the same size (the first element is parray[0]). Pascal array index ranges can include negative numbers!

Characteristics

Elements of an array are usually specified with a 0-first index, for example, myarray[0] would represent the first element of myarray. myarray[n] (where n is the length of the array minus 1) would represent the last element in the array. However, some languages such as old Fortran and Lua use 1 as the initial index.

Some languages (C++, Java, C#) have "basic arrays" and collections. Basic arrays are supported by the compiler directly, have a fixed size, and only provide element access by index. Collections, like Java's ArrayList, are system library classes implemented on the top of these basic arrays and have a wide range of various methods. In such cases, the tag should be used to name the simple arrays.

Arrays can be statically allocated or dynamically allocated. The way in which you access the array and its type varies based on how it is declared and allocated.

Arrays can contain multiple indices. For example, an array with one index (e.g. array[0]) is known as a one-dimensional array. If it has two indices (e.g. array[0][0]) it is considered two dimensional and maybe visualized as a grid. Multidimensional arrays, or, in other words, arrays with multiple indices are called matrices, or a matrix is singular.

References

Related tags

Where talking about specific variants of arrays, use these related tags instead:

414766 questions
2320
votes
54 answers

Remove duplicate values from JS array

I have a very simple JavaScript array that may or may not contain duplicates. var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"]; I need to remove the duplicates and put the unique values in a new array. I could point to all the code…
kramden88
  • 23,477
  • 3
  • 19
  • 17
2271
votes
12 answers

How can I add new array elements at the beginning of an array in JavaScript?

I have a need to add or prepend elements at the beginning of an array. For example, if my array looks like below: [23, 45, 12, 67] And the response from my AJAX call is 34, I want the updated array to be like the following: [34, 23, 45, 12,…
Moon
  • 33,439
  • 20
  • 81
  • 132
2230
votes
78 answers

How to create an array containing 1...N

I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime. var foo = []; for (var i = 1; i <= N; i++) { foo.push(i); } To me it feels like there should be a way of…
Godders
  • 22,776
  • 4
  • 19
  • 19
2204
votes
21 answers

Loop through an array of strings in Bash?

I want to write a script that loops through 15 strings (array possibly?) Is that possible? Something like: for databaseName in listOfNames then # Do something end
Mo.
  • 40,243
  • 37
  • 86
  • 131
2193
votes
17 answers

How do I empty an array in JavaScript?

Is there a way to empty an array and if so possibly with .remove()? For instance, A = [1,2,3,4]; How can I empty that?
akano1
  • 40,596
  • 19
  • 54
  • 67
2148
votes
31 answers

Short circuit Array.forEach like calling break

[1,2,3].forEach(function(el) { if(el === 1) break; }); How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
Scott Klarenbach
  • 37,171
  • 15
  • 62
  • 91
2109
votes
40 answers

Copy array by value

When copying an array in JavaScript to another array: var arr1 = ['a','b','c']; var arr2 = arr1; arr2.push('d'); // Now, arr1 = ['a','b','c','d'] I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can…
Dan
  • 21,377
  • 5
  • 18
  • 16
2099
votes
36 answers

Find object by id in an array of JavaScript objects

I've got an array: myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}, etc.] I'm unable to change the structure of the array. I'm being passed an id of 45, and I want to get 'bar' for that object in the array. How do I do this in…
thugsb
  • 22,856
  • 6
  • 30
  • 44
2088
votes
26 answers

How do I check if a variable is an array in JavaScript?

How do I check if a variable is an array in JavaScript? if (variable.constructor == Array)
Andy McCluggage
  • 37,618
  • 18
  • 59
  • 69
2062
votes
28 answers

Why is using "for...in" for array iteration a bad idea?

I've been told not to use for...in with arrays in JavaScript. Why not?
lYriCAlsSH
  • 57,436
  • 10
  • 26
  • 20
2040
votes
63 answers

Get the last item in an array

Here is my JavaScript code so far: var linkElement = document.getElementById("BackButton"); var loc_array = document.location.href.split('/'); var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));…
balexander
  • 23,131
  • 14
  • 45
  • 68
1993
votes
71 answers

How to randomize (shuffle) a JavaScript array?

I have an array like this: var arr1 = ["a", "b", "c", "d"]; How can I randomize / shuffle it?
Ali
  • 261,656
  • 265
  • 575
  • 769
1935
votes
89 answers

How to merge two arrays in JavaScript and de-duplicate items

I have two JavaScript arrays: var array1 = ["Vijendra","Singh"]; var array2 = ["Singh", "Shakya"]; I want the output to be: var array3 = ["Vijendra","Singh","Shakya"]; The output array should have repeated words removed. How do I merge two arrays…
Vijjendra
  • 24,223
  • 12
  • 60
  • 92
1794
votes
20 answers

With arrays, why is it the case that a[5] == 5[a]?

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] ==…
Dinah
  • 52,922
  • 30
  • 133
  • 149
1683
votes
34 answers

Sorting an array of objects by property values

I've got the following objects using AJAX and stored them in an array: var homes = [ { "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { "h_id": "4", …
TomHankers