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
69
votes
11 answers

Numpy: For every element in one array, find the index in another array

I have two 1D arrays, x & y, one smaller than the other. I'm trying to find the index of every element of y in x. I've found two naive ways to do this, the first is slow, and the second memory-intensive. The slow way indices= [] for iy in y: …
Chris
  • 1,109
  • 2
  • 11
  • 16
69
votes
7 answers

Group rows in an associative array of associative arrays by column value and preserve the original first level keys

I have an array of subarrays in the following format: [ 'a' => ['id' => 20, 'name' => 'chimpanzee'], 'b' => ['id' => 40, 'name' => 'meeting'], 'c' => ['id' => 20, 'name' => 'dynasty'], 'd' => ['id' => 50, 'name' => 'chocolate'], …
Anson Kao
  • 5,256
  • 4
  • 28
  • 37
69
votes
8 answers

Find the first element in a sorted array that is greater than the target

In a general binary search, we are looking for a value which appears in the array. Sometimes, however, we need to find the first element which is either greater or less than a target. Here is my ugly, incomplete solution: // Assume all elements are…
SecureFish
  • 2,391
  • 7
  • 32
  • 43
69
votes
7 answers

What is the shortest way to initialize List of strings in java?

I am searching for the shortest way (in code) to initialize list of strings and array of strings, i.e. list/array containing "s1", "s2", "s3" string elements.
Vladimir
  • 12,753
  • 19
  • 62
  • 77
69
votes
16 answers

How to clone an array of objects in PHP?

I have an array of objects. I know that objects get assigned by "reference" and arrays by "value". But when I assign the array, each element of the array is referencing the object, so when I modify an object in either array the changes are reflected…
DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
69
votes
4 answers

Creating integer array of resource IDs

I have some images in my res/drawable folder. Let's say img1.png, img2.png and img3.png. I am currently creating an integer array of these image IDs in Java like this int[] imgIds = {R.drawable.img1, R.drawable.img2, R.drawable.img3}; Instead, is…
android_stricken
  • 703
  • 1
  • 5
  • 5
69
votes
2 answers

Apply function on each row (row-wise) of a NumPy array

So, I have the function - def function(x): x , y = vector return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2) and let's say that I would like to evaluate it at the following points (first column are the x-values and second column…
tattybojangler
  • 1,003
  • 3
  • 15
  • 25
69
votes
6 answers

Convert JSON string to array of JSON objects in Javascript

I would like to convert this string {"id":1,"name":"Test1"},{"id":2,"name":"Test2"} to array of 2 JSON objects. How should I do it? best
Sobis
  • 1,385
  • 4
  • 20
  • 29
69
votes
11 answers

C#: Limit the length of a string?

I was just simply wondering how I could limit the length of a string in C#. string foo = "1234567890"; Say we have that. How can I limit foo to say, 5 characters?
Lemmons
  • 1,738
  • 4
  • 23
  • 33
69
votes
5 answers

"error: assignment to expression with array type error" when I assign a struct field (C)

I'm a beginner C programmer, yesterday I learned the use of C structs and the possible application of these ones about the resolution of specific problems. However when I was experimenting with my C IDE (Codeblocks 16.01) in order to learn this…
p4nzer96
  • 815
  • 1
  • 7
  • 6
69
votes
8 answers

How can I force PHP to use strings for array keys?

I've come across an old app that uses an id to name type array, for example... array(1) { [280]=> string(3) "abc" } Now I need to reorder these, and a var_dump() would make it appear that that isn't going to happen while the keys are…
alex
  • 479,566
  • 201
  • 878
  • 984
69
votes
3 answers

Swift performance: map() and reduce() vs for loops

I'm writing some performance-critical code in Swift. After implementing all the optimizations I could think of, and profiling the application in Instruments, I came to realize that the vast majority of CPU cycles are spent performing map() and…
Hundley
  • 3,167
  • 3
  • 23
  • 45
69
votes
9 answers

PHP: Get key from array?

I am sure that this is super easy and built-in function in PHP, but I have yet not seen it. Here's what I am doing for the moment: foreach($array as $key => $value) { echo $key; // Would output "subkey" in the example array …
Industrial
  • 41,400
  • 69
  • 194
  • 289
69
votes
11 answers

Most efficient way to append arrays in C#?

I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve. What is the most efficient way to concatenate these arrays together in C# as I pull them …
Huck
  • 967
  • 2
  • 9
  • 10
69
votes
6 answers

How to filter a two dimensional array by value

How would I create a function that filters a two dimensional array by value? Given the following array : Array ( [0] => Array ( [interval] => 2014-10-26 [leads] => 0 [name] => CarEnquiry …
aphextwix
  • 1,838
  • 3
  • 21
  • 27
1 2 3
99
100