Built-in Functions for Manipulating Arrays
Last updated
Last updated
introduced two built-in functions: push() and pop(). This section will explore a few more.
len() is used to get the number of elements in an array (i.e the length of the array).
slice() returns a section of the array (i.e slices it). The first argument to slice must be an array or string. The second and third arguments to slice() are optional and are named start and end.
start: specifies where to start slicing from (i.e the index of the first element in the array or string that will be returned.)
end: specifies where to stop slicing at (i.e the index of the element one level above the last element to return).
slice() can also take a fourth, optional, argument. This argument is called step and it is used to specify a "step" or "skip" value for the slice operation. The step value allows the slice() function to skip certain elements in the original array depending on whether the modulus of the index of the element and the step value is equal to 0.
If this sounds really complex, the following example will explain:
contains() checks whether an array or string contains a certain element (which can be a string, number, boolean, map, function or another array).
index() requires two arguments: an array or string, and a value (number, string, etc). It returns the index of the first occurrence of value in the array or string.
If value wasn't found at all, index() returns -1.
sort() sorts an array's elements in ascending order and returns a new array containing the sorted elements. It does not change the order of original array.
String elements can be sorted too.
Feel free to skip this section if you have never studied sorting algorithms.
The sort algorithm Sonar uses is based on Go's pdqsort (Pattern-defeating quicksort) algorithm. Without launching into a deep conversation into sorting algorithms and their trade-offs, we can state here that the decision to base Sonar's sort() on Go's pdqsort was made for the following reasons:
pdqsort is a very fast algorithm
No other reason
reverse() reverses the position of an array's elements, and returns a new array with the new order. The original array is left unchanged.
Given that Sonar's sort() is based on pdqsort, it is a fast, albeit non-"stable" sort implementation. Please, note that "non-stable", as used here, does not mean "un-reliable". See this .)
sort() sorts elements according to their position in the .