JavaScript. Methods that receive data from an array without changing the array itself

Methods that receive data from an array without changing the array itself:
indexOf(), lastIndexOf(), find(), findIndex(), slice(), concat(), toString(), join()


Contents


Search on other resources:

1. Methods indexOf() and lastIndexOf(). Return the positions of the first and last occurrence of an element in the array

The indexOf() and lastIndexOf() methods return the positions of the first and last occurrences of a given element in an array. Using methods looks something like this

firstPos = array.indexOf(item)
lastPos = array.lastIndexOf(item)

here

  • array – the array in which the search is performed;
  • firstPos – the position of the first occurrence of the element item in the array;
  • lastPos is the position of the last occurrence of item in the array.

If item is not in array, the functions return -1.

Example.

// Functions indexOf() and lastIndexOf()
// Get the position of the first and last occurrence of a given element in the array

// 1. Processing an array of integers
// 1.1. Declare the array of numbers and output it
var A = new Array(2, 8, 3, 5, 4, 1, 2, 3, 4, 4, 5, 2)
console.log("A:")
console.log(A)

// 1.2. Get positions of first and last occurrence 4
var first = A.indexOf(4)
var last = A.lastIndexOf(4)
console.log("A.indexOf(4) = " + first)
console.log("A.lastIndexOf(4) = " + last)

// 1.3. Get positions of non-existent element 9
first = A.indexOf(9) // first = -1
last = A.lastIndexOf(11) // last = -1
console.log("A.indexOf(9) = " + first)
console.log("A.lastIndexOf(11) = " + last)

// 2. Processing the array of strings. Search for a string
// 2.1. Объявить массив строк и вывести его
var S = ["abc", "def", "jklm", "ghi", "", "def", "jprst"]
console.log("--------------------------------")
console.log("S:")
console.log(S)

// 2.2. Determine the position of the first and last occurrence
//      of the string "jprst" in the array S
first = S.indexOf("jprst")
last = S.lastIndexOf("jprst")
console.log("A.indexOf(\"jprst\") = " + first)
console.log("A.lastIndexOf(\"jprst\") = " + last)
console.log("Ok");

Result

A:
[
2, 8, 3, 5, 4,
1, 2, 3, 4, 4,
5, 2
]
A.indexOf(4) = 4
A.lastIndexOf(4) = 9
A.indexOf(9) = -1
A.lastIndexOf(11) = -1
--------------------------------
S:
[
'abc', 'def',
'jklm', 'ghi',
'', 'def',
'jprst'
]
A.indexOf("jprst") = 6
A.lastIndexOf("jprst") = 6
Ok

 

2. Method find(). Finding the element in the array that matches a given criterion

The find() method returns an array element that matches the given criteria. The criterion is formed in the special function or lambda function.

Using the find() method in a program might look something like this

item = array.find(Func)

where

  • array – source array;
  • item – the desired element from the array array, for which the Func() function returns true. If item is not in the array, undefined is returned;
  • Func – the name of the function and the lambda expression (lambda function) that returns true or false. This function (expression) specifies the code by which it is determined whether the array element satisfies the required criterion.

The function declaration looks something like this

function Func(value, index, array) {
  // Performing actions that return true or false
  // ...
}

where

  • value – the current value of the array being considered;
  • index – the position of the current value of array. Thus array[index]==value;
  • array – the name of the array in question.

If a single value value is enough to define the criterion, the index and array parameters in the Func function can be omitted

function Func(value) {
  // Performing actions that return true or false
  // ...
}

Example.

// Method find(). Get the array element that first matches the specified criteria.
// Task. Find an element that is within [40; fifty].

// 1. Search in the array of numbers
// 1.1. The source array of numbers
var A = new Array( 10, 21, 32, 131, 44, 25, 6, 17 )

// 1.2. A function that determines whether an element matches the specified criteria,
// or whether the element's value is in the range [40; fifty]
function Range_40_50(value, index, array) {
  if ((array[index] >= 40) && (array[index] <= 50))
    return true
  else
    return false
}

// 1.3. Find element
var item = A.find(Range_40_50) // item = 44

// 1.4. Display the element
console.log("item = " + item)

// 2. Search in the array of strings. Find first string starting with letter 'c'
// 2.1. The source array
var S = ["abc", "ac", "bcd", "cde", "bda", "bd", "cbcd"]

// 2.2. Declare a lambda function when calling the find() function.
// The lambda function determines if the first character in the string 'c' is.
var str = S.find((value) => value[0] == 'c');

// 2.3. Display the result
console.log("str = " + str) // str = cde

Result

item = 44
str = cde

 

3. Method findIndex(). Get the index of the array element that matches the given criteria

The findIndex() method returns the position (index) of the element that satisfies the specified criteria. The criterion is defined by a given function or lambda function. The method is similar to the find() method, only its position is returned instead of the element itself.

The use of the method in the program is as follows

index = array.findIndex(Func)

where

  • array – an array in which the element is searched;
  • index is the position to be found;
  • Func is a function (lambda function) that returns true or false. It is the expression that generates the true value that determines the selection criterion for the required element.

In turn, the Func() function is declared in one of two ways, depending on the need to use certain parameters

function Func(value, index, obj) {
  // Actions to be performed
  // ...
}

or

function Func(value) {
  // Actions to be performed
  // ...
}

where

  • obj – array to be processed;
  • value – the value of the element from the obj array. For this value, the equality value==obj[index];
  • index – position of the element in the obj array.

Also, instead of a function, it is possible to use a lambda function like

(value, index, obj) => expression

or

(value) => expression

here

  • expression – conditional expression that returns true or false.

Example.

// Method findIndex().
// Find an element that matches the specified criteria

// 1. Task. Find the first negative element of the array.
// 1.1. The original array of numbers
var A1 = new Array( 10, 21, -12, 33, -41, 55, 60, 87 )

// 1.2. Declare a function that returns true if value<0
function Is_Negative(value, index, obj) {
  return obj[index] < 0
}

// 1.3. The findIndex() call is to find the index of the negative element.
var index = A1.findIndex(Is_Negative)

// 1.4. Print the result
console.log("A1 = " + A1)
console.log("index = " + index)

// 2. Task. Find the index of the first string that is longer than 3 characters.
// 2.1. Declare the array of strings
var B1 = ["ab", "abc", "abcd", "", "jklmn", ""]

// 2.2. Form a lambda function that returns true
// if the string length is 4 or more characters
var expr = (value) => value.length >= 4

// 2.3. Call the findIndex() method
index = B1.findIndex(expr)

// 2.4. Display the result
console.log("B1 = " + B1)
console.log("index = " + index)

Result

A1 = 10,21,-12,33,-41,55,60,87
index = 2
B1 = ab,abc,abcd,,jklmn,
index = 2

 

4. Method slice(). Get a subarray from the given array

Using the slice() method, you can get a subarray from a given array. In this case, the boundaries of the subarray can be set in different ways. Accordingly, the slice() method has 3 use cases.

array2 = array1.slice()
array2 = array1.slice(a)
array2 = array1.slice(a, b)

here

  • array1 – the source array;
  • array2 – the resulting subarray obtained from the original array1 and the values a, b;
  • a, b – the lower and upper indices of the subarray range, respectively. The superscript b indicates the position of the element following the last element of the resulting subarray.

The first implementation of the slice() method with no parameters returns the entire original array. The second implementation of the method with one parameter returns a subarray that starts at the value of that parameter and goes to the end of the array. The third implementation returns a subarray defined by the index range [a; b] of the original array.

Example.

// Method slice().Get a subarray from the specified array
// 1. Declare array of numbers
var A1 = new Array(0, 1, 2, 3, 4, 5, 6, 7)

// 2. Get subarray

var A2 = A1.slice(2, 4) // A2 = [ 2,3 ]
var A3 = A1.slice() // A3 = [ 0,1,2,3,4,5,6,7 ]
var A4 = A1.slice(5) // A4 = [ 5,6,7 ]

// 3. Display arrays A2 and A3
console.log("A2 => " + A2)
console.log("A3 => " + A3)
console.log("A4 => " + A4)

Результат

A2 => 2,3
A3 => 0,1,2,3,4,5,6,7
A4 => 5,6,7

 

5. Method concat(). Get a new array padded with other elements and arrays

The concat() method allows you to get a new array, which is formed by adding other arrays or elements to the current array.

In a simplified form, the applying of the method is as follows:

Res = A.concat(item1, item2, ..., itemN)

where

  • item1, item2, itemN – separate elements or arrays;
  • A – the array to which the elements (arrays) item1, item2, itemN are added;
  • Res – resulting array, which is the addition of array A1 and arrays (elements) item1, item2, itemN.

The following is an example of using the concat() method.

// Methods for working with arrays

// Function concat().
// Concatenates arrays
// 1. For integers
// 1.1. Declare 2 arrays
var A1 = new Array(2, 8, 3, 5, 4, 1)
var A2 = new Array(3, 11, 7, 6)

// 1.2. Add to array A1 array A2 and array [10, 20]
A1 = A1.concat(A2, [10, 20])

// 1.3. Display the A1 array
document.write("A1:<br>")
for (var i = 0; i < A1.length; i++)
  document.write(A1[i] + " ")
document.write("<br>")

// 2. For objects of different types
// 2.1. Create 2 objects
A1 = [ "abc", true, 23, 0.005 ]
A2 = [ "Hello", '+' ]

// 2.2. Add one array and one element to array A2
A2 = A2.concat(A1, 777)

// 2.3. Display the A2 array
document.write("A2:<br>")
for (var i = 0; i < A2.length; i++)
  document.write(A2[i] + " ")
document.write("<br>")

Result

A1:
2 8 3 5 4 1 3 11 7 6 10 20
A2:
Hello + abc true 23 0.005 777

 

6. Method toString(). Convert array to string

Using the to String() method, you can convert an array to a string. The use of the method is as follows

str = array.toString()

where

  • array – array of elements;
  • str – resulting string.

Example.

// Method toString(). Convert array to string

// 1. Array of numbers
var A = new Array( 0, 1, 2, 3, 4, 5, 6, 7 )
var str = A.toString()
console.log(str) // str = "0,1,2,3,4,5,6,7"

// 2. Array of elements of different types
var B = [true, 2.88, '+', "abcd"]
str = B.toString()
console.log(str)

Result

0,1,2,3,4,5,6,7
true,2.88,+,abcd

 

7. Method join(). Merge all array elements into one string

The join() method returns a character string containing all the elements of the array separated by the given character or string. The character or string separating the elements is specified as an argument to the join() method.

The program uses the join() method in one of two ways. The first way involves using the argument

str = array.join(separator)

where

  • array – the array whose elements are formed into the string str;
  • str – resulting string;
  • separator – delimiter character or delimiter string.

The second way involves calling the method without parameters

str = array.join()

In this case, the separator is set to ‘ , ‘ (comma).

Example.

// Function join()
// Concatenate all elements of the array with the given delimiter into a string.

// 1. Processing an array of integers
// 1.1. Declare an array of numbers and output it
var A = new Array(2, 8, 3, 5, 4, 1, 2, 3, 4, 4, 5, 2)
console.log("A:")
console.log(A)

// 1.2. Call the join() method with parameter
var str = A.join('+')
console.log(str)

// 1.3. Call the join() without a parameter
str = A.join() // A.join(',') - default character ',' (comma)
console.log(str)

// 2. Processing the array of real numbers
// 2.1. Declare the array of numbers and output it
var B = [2.8, 3.5, -1.4, -0.9905]
console.log("------------------------")
console.log("B:")
console.log(B)

// 2.2. Call the join() method
str = B.join(" ") // a string with 2 spaces is specified
console.log(str)

console.log("Ok");

Result

A:
[
2, 8, 3, 5, 4,
1, 2, 3, 4, 4,
5, 2
]
2+8+3+5+4+1+2+3+4+4+5+2
2,8,3,5,4,1,2,3,4,4,5,2
------------------------
B:
[ 2.8, 3.5, -1.4, -0.9905 ]
2.8 3.5 -1.4 -0.9905
Ok

 


Related topics