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
74
votes
7 answers

Sort Objects in Array by date

I have an array containing an object called HistoryObject and it has properties such as "date", "name", etc. I am sorting the array like so: let sortedArray = HistoryArray.sort({ $0.date.compare($1.date) ==…
Nata Mio
  • 2,168
  • 3
  • 22
  • 46
74
votes
6 answers

Convert Map to JavaScript object

So Ive got the following javascript which contains a key/value pair to map a nested path to a directory. function createPaths(aliases, propName, path) { aliases.set(propName, path); } map = new Map(); createPaths(map,…
nixgadget
  • 6,983
  • 16
  • 70
  • 103
74
votes
9 answers

Using lodash push to an array only if value doesn't exist?

I'm trying to make an array that if a value doesn't exist then it is added but however if the value is there I would like to remove that value from the array as well. Feels like Lodash should be able to do something like this. I'm interested in…
Max Lynn
  • 1,738
  • 6
  • 22
  • 35
74
votes
23 answers

Find the 2nd largest element in an array with minimum number of comparisons

For an array of size N, what is the number of comparisons required?
nababa
  • 1,251
  • 3
  • 13
  • 20
74
votes
6 answers

Using the reduce function to return an array

Why is it that when I want to use the push function inside the reduce function to return a new array I get an error. However, when I use the concat method inside the reduce function, it returns a new array with no problem. All I'm trying to do is…
2K01B5
  • 1,011
  • 1
  • 10
  • 23
74
votes
8 answers

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

What’s the difference between “{}” and “[]” while declaring a JavaScript array? Normally I declare like var a=[]; What is the meaning of declaring the array as var a={}
Venkat
  • 2,549
  • 2
  • 28
  • 61
74
votes
2 answers

Numpy minimum in (row, column) format

How can I know the (row, column) index of the minimum of a numpy array/matrix? For example, if A = array([[1, 2], [3, 0]]), I want to get (1, 1) Thanks!
yassin
  • 6,529
  • 7
  • 34
  • 39
74
votes
19 answers

How to find a duplicate element in an array of shuffled consecutive integers?

I recently came across a question somewhere: Suppose you have an array of 1001 integers. The integers are in random order, but you know each of the integers is between 1 and 1000 (inclusive). In addition, each number appears only once in the array,…
SysAdmin
  • 5,455
  • 8
  • 33
  • 34
74
votes
1 answer

Store grep output in an array

I need to search a pattern in a directory and save the names of the files which contain it in an array. Searching for pattern: grep -HR "pattern" . | cut -d: -f1 This prints me all filenames that contain "pattern". If I try: targets=$(grep -HR…
Luca Davanzo
  • 21,000
  • 15
  • 120
  • 146
74
votes
7 answers

How to access nested elements of json object using getJSONArray method

I have a JSON response that looks like this: { "result": { "map": { "entry": [ { "key": { "@xsi.type": "xs:string", "$": "ContentA" }, "value": "fsdf" }, { "key": { "@xsi.type":…
Sriks
  • 1,669
  • 6
  • 26
  • 40
74
votes
10 answers

find out the elements of an arraylist which is not present in another arraylist

I have to find a best way to find out that elements which is not presented in the second arraylist. suppose Arraylist a,b, Arraylist a={1,2,3,4,5}; Arraylist b={2,3,4}; So basically what I want is to find out that elements of a which is not…
arvin_codeHunk
  • 2,328
  • 8
  • 32
  • 47
74
votes
3 answers

When a function has a specific-size array parameter, why is it replaced with a pointer?

Given the following program, #include using namespace std; void foo( char a[100] ) { cout << "foo() " << sizeof( a ) << endl; } int main() { char bar[100] = { 0 }; cout << "main() " << sizeof( bar ) << endl; foo( bar…
CsTamas
  • 4,103
  • 5
  • 31
  • 34
74
votes
5 answers

Dividing elements of a ruby array into an exact number of (nearly) equal-sized sub-arrays

I need a way to split an array in to an exact number of smaller arrays of roughly-equal size. Anyone have any method of doing this? For instance a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] groups = a.method_i_need(3) groups.inspect =>…
Red
  • 2,256
  • 5
  • 25
  • 38
74
votes
8 answers

Sort Array by ISO 8601 date

How can I sort this array by date (ISO 8601)? var myArray = new Array(); myArray[0] = { name:'oldest', date:'2007-01-17T08:00:00Z' } myArray[1] = { name:'newest', date:'2011-01-28T08:00:00Z' } myArray[2] = { name:'old', …
Peter
  • 11,413
  • 31
  • 100
  • 152
74
votes
3 answers

array.array versus numpy.array

If you are creating a 1d array in Python, is there any benefit to using the NumPy package?
Hortitude
  • 13,638
  • 16
  • 58
  • 72