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
73
votes
6 answers

Adding items to an object through the .push() method

I'm doing a loop through few input elements of 'checkbox' type. After that, I'm adding values and checked attributes to an array. This is my code: var stuff = {}; $('form input[type=checkbox]').each(function() { stuff[$(this).attr('value')] =…
dperitch
  • 1,869
  • 2
  • 17
  • 22
73
votes
8 answers

boolean[] vs. BitSet: Which is more efficient?

What is more efficient in terms of memory and CPU usage — an array of booleans or a BitSet? Specific BitSet methods are not used, only get/set/clear (==, =, Arrays.fill respectively for an array).
Maxim
73
votes
14 answers

How to count duplicate elements in a Ruby array

I have a sorted array: [ 'FATAL ', 'FATAL ', 'FATAL ' ] I would like to get something like this but it…
Željko Filipin
  • 56,372
  • 28
  • 94
  • 125
73
votes
10 answers

JavaScript - get array element fulfilling a condition

I'm learning JavaScript using W3C and I didn't find an answer to this question. I'm trying to make some manipulations on array elements which fulfill some condition. Is there a way to do it other than running on the array elements in for loop? Maybe…
Day_Dreamer
  • 3,311
  • 7
  • 34
  • 61
73
votes
10 answers

How do I check in Swift if two arrays contain the same elements regardless of the order in which those elements appear in?

Let's say there are two arrays... var array1 = ["a", "b", "c"] var array2 = ["b", "c", "a"] I'd like the result of the comparison of these two arrays to be true, and the following... var array1 = ["a", "b", "c"] var array2 = ["b", "c", "a",…
73
votes
3 answers

Remove object from array knowing its id

I have an array of objects: var myArr; Let’s say that on page load it contains 10 objects with the following structure: { Id: …, Name: … } How can I remove an object from myArr by its Id?
user1765862
  • 13,635
  • 28
  • 115
  • 220
73
votes
15 answers

Find last matching object in array of objects

I have an array of objects. I need to get the object type ("shape" in this example) of the last object, remove it, and then find the index of the previous object in the array that has the same type, e.g. "shape". var fruits = [ { shape:…
Graeck
  • 1,326
  • 1
  • 11
  • 15
73
votes
13 answers

If (Array.Length == 0)

If an array is empty, it looks like you can't check it's length using ".length". What's the best way to check if an array is empty?
sooprise
  • 22,657
  • 67
  • 188
  • 276
73
votes
11 answers

Filter array of objects with another array of objects

This question is similar to this one Jquery filter array of object with loop but this time I need to do the filter with an array of objects. Exemple: I have an array of objects like this: myArray = [ { userid: "100", projectid: "10", …
GtAntoine
  • 1,049
  • 1
  • 8
  • 12
73
votes
5 answers

Sorting an almost sorted array (elements misplaced by no more than k)

I was asked this interview question recently: You're given an array that is almost sorted, in that each of the N elements may be misplaced by no more than k positions from the correct sorted order. Find a space-and-time efficient algorithm to sort…
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
73
votes
9 answers

Python: find position of element in array

I have a CSV containing weather data like max and min temperatures, precipitation, longitude and latitude of the weather stations etc. Each category of data is stored in a single column. I want to find the location of the maximum and minimum…
julesjanker
  • 787
  • 1
  • 7
  • 9
73
votes
7 answers

How can I store regex captures in an array in Perl?

Is it possible to store all matches for a regular expression into an array? I know I can use ($1,...,$n) = m/expr/g;, but it seems as though that can only be used if you know the number of matches you are looking for. I have tried my @array =…
cskwrd
  • 2,803
  • 8
  • 38
  • 51
73
votes
10 answers

How do you initialise a dynamic array in C++?

How do I achieve the dynamic equivalent of this static array initialisation: char c[2] = {}; // Sets all members to '\0'; In other words, create a dynamic array with all values initialised to the termination character: char* c = new char[length];…
tgh
  • 765
  • 1
  • 5
  • 7
73
votes
7 answers

Best way to check if a character array is empty

Which is the most reliable way to check if a character array is empty? char text[50]; if(strlen(text) == 0) {} or if(text[0] == '\0') {} or do i need to do memset(text, 0, sizeof(text)); if(strlen(text) == 0) {} Whats the most efficient way…
ZPS
  • 1,566
  • 4
  • 16
  • 20
73
votes
5 answers

Doctrine array vs simple_array vs json_array

I am using symfony and doctrine as my ORM. For available types I have: array simple_array json_array I am wondering what the difference is between each of them: when do I use one or the other? Can I have a demonstration for each of them to…
0x1gene
  • 3,349
  • 4
  • 29
  • 48