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
1368
votes
32 answers

How to sort an array of integers correctly

Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought. var numArray = [140000, 104, 99]; numArray = numArray.sort(); console.log(numArray) I'd expect this to show 99,…
peirix
  • 36,512
  • 23
  • 96
  • 126
1355
votes
37 answers

How to remove item from array by value?

Is there a method to remove an item from a JavaScript array? Given an array: var ary = ['three', 'seven', 'eleven']; I would like to do something like: removeItem('seven', ary); I've looked into splice() but that only removes by the position…
MacMac
  • 34,294
  • 55
  • 151
  • 222
1353
votes
29 answers

"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP

I'm running a PHP script and continue to receive errors like: Notice: Undefined variable: my_variable_name in C:\wamp\www\mypath\index.php on line 10 Notice: Undefined index: my_index C:\wamp\www\mypath\index.php on line 11 Warning: Undefined array…
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1337
votes
28 answers

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

I have an array like vendors = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' } // and so on... ]; How do I check this array to see if "Magenic" exists? I don't want to loop, unless I have to. I'm working with…
David Lozzi
  • 14,697
  • 9
  • 28
  • 44
1314
votes
84 answers

How to get the difference between two arrays in JavaScript?

Is there a way to return the difference between two arrays in JavaScript? For example: var a1 = ['a', 'b']; var a2 = ['a', 'b', 'c', 'd']; // need ["c", "d"]
John Adawan
  • 13,329
  • 4
  • 20
  • 11
1311
votes
39 answers

Get the first element of an array

I have an array: array( 4 => 'apple', 7 => 'orange', 13 => 'plum' ) I would like to get the first element of this array. Expected result: string apple One requirement: it cannot be done with passing by reference, so array_shift is not a good…
hsz
  • 148,279
  • 62
  • 259
  • 315
1282
votes
17 answers

Get JavaScript object from array of objects by value of property

Let's say I have an array of four objects: var jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ]; Is there a way that I can get the third object ({a: 5, b: 6}) by the value of the property b for example without a…
user765368
  • 19,590
  • 27
  • 96
  • 167
1275
votes
49 answers

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I had an interesting job interview experience a while back. The question started really easy: Q1: We have a bag containing numbers 1, 2, 3, …, 100. Each number appears exactly once, so there are 100 numbers. Now one number is randomly picked out of…
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
1269
votes
25 answers

Converting array to list in Java

How do I convert an array to a list in Java? I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour. For example: int[]…
Alexandru
  • 25,070
  • 18
  • 69
  • 78
1267
votes
38 answers

Reference - What does this error mean in PHP?

What is this? This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix them. This is also a Community Wiki, so everyone is invited to participate adding to and maintaining…
hakre
  • 193,403
  • 52
  • 435
  • 836
1265
votes
17 answers

Converting 'ArrayList to 'String[]' in Java

How might I convert an ArrayList object to a String[] array in Java?
Alex
  • 16,375
  • 7
  • 22
  • 19
1230
votes
32 answers

How to create a generic array in Java?

Due to the implementation of Java generics, you can't have code like this: public class GenSet { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation } } How can I implement…
tatsuhirosatou
  • 25,149
  • 14
  • 39
  • 40
1216
votes
6 answers

Convert ArrayList to String[] array

I'm working in the android environment and have tried the following code, but it doesn't seem to be working. String [] stockArr = (String[]) stock_list.toArray(); If I define as follows: String [] stockArr = {"hello", "world"}; it works. Is there…
locoboy
  • 38,002
  • 70
  • 184
  • 260
1201
votes
20 answers

Copy array items into another array

I have a JavaScript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the items into the new array: var newArray =…
bba
  • 14,621
  • 11
  • 29
  • 26
1163
votes
20 answers

Difference between ( for... in ) and ( for... of ) statements?

I know what is a for... in loop (it iterates over the keys), but I have heard about for... of for the first time (it iterates over values). I am confused about for... of loop. var arr = [3, 5, 7]; arr.foo = "hello"; for (var i in arr) { …
Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79