JavaScript. Methods that modify array. Part 1

Methods that modify array. Part 1. Methods sort(), reverse(), forEach(), filter(), map(), copyWithin(), splice()


Contents


Search on other Web-resources:

1. Method sort(). Sort array in ascending order

The sort() method returns a sorted array. The simplest implementation of the method sorts the array in ascending order. In this case, the use of the method has several options.

Way 1. Sorting in ascending order. Here you can create a comparison expression

array.sort((a, b) => a - b)

or a comparison function with the corresponding call

// comparison function
function Compare(a, b) {
  return a - b
}

// call the sort() method
array.sort(Compare)

In the above code:

  • array – array to be sorted;
  • a, b – two conditional values that determine the sign of the result. If a<b, then the difference between a-b is negative and the array is sorted in ascending order. If a>=b, then the result of a-b is positive and the array is sorted in descending order.

Way 2. Sort in descending order. In this case, the expression will look like

array.sort((a, b) => b - a) // a-b => b-a

The comparison function will be different.

// Comparison function
function Compare(a, b) {
  return b - a
}

// call the sort() method
array.sort(Compare)

Example.

// Method sort(). Sorting

// 1. Sort array of numbers in descending order
// 1.1. Declare array of numbers
var A1 = new Array( 2.8, 3.3, -1.6, 5.8, 5.5, 1.4, -7.2 )

// 1.2. Declare a comparison function
function Compare(a, b) {
  return a - b
}

// 1.3. Sort an array in descending order
var A2 = A1.sort(Compare)

// 1.4. Display the result
console.log("A1 = " + A1)
console.log("A2 = " + A2)

// 2. Sort array A1 in descending order
// 2.1. Declare a sorting expression, but instead of a-b specify b-a
var A3 = A1.sort((a, b) => b - a);

// 2.2. Display the result
console.log("A1 = " + A1)
console.log("A3 = " + A3)

Result

A1 = -7.2,-1.6,1.4,2.8,3.3,5.5,5.8
A2 = -7.2,-1.6,1.4,2.8,3.3,5.5,5.8
A1 = 5.8,5.5,3.3,2.8,1.4,-1.6,-7.2
A3 = 5.8,5.5,3.3,2.8,1.4,-1.6,-7.2

 

2. Method reverse(). Arrange array elements in reverse order

The reverse() method returns an array in which the elements are placed in the reverse order of the original array. The method does not receive parameters and can be used in the program as follows

array1.reverse()
array2 = array1.reverse()

where

  • array1 – the array being reversed. After calling reverse(), this array also changes;
  • array2 – a copy of the reversed array array1.

The reverse() method returns a reversed array.

Example.

// Method reverse(). Reversing an array.

// 1. Declare an array of numbers
var A1 = new Array(1, 2, 3, 4, 5, 6, 7)

// 2. Reverse array
var A2 = A1.reverse()

// 3. Display arrays A1, A2
console.log("A1 => " + A1)
console.log("A2 => " + A2)

console.log("Ok");

Result

A1 => 7,6,5,4,3,2,1
A2 => 7,6,5,4,3,2,1
Ok

 

3. Method forEach(). Execute the given function for each element of the array

The forEach() method allows you to perform a specified operation on each element of the array. For example, each element of the array of numbers can be multiplied by 5.

Calling the forEach() method on an array object looks like this

array.forEach(Func)

where

  • array – processed array. This array is changing;
  • Func is the name of the callback function that performs operation on an array element.

The callback function takes 3 parameters and in the program should have something like the following declaration

function Func(value, index, array)
{
  // Actions that modify array[index]
  // ...
}

where

  • value – value of array[index] array element;
  • index – position of the value array element;
  • array – directly processed array.

Example.

The example shows:

  • multiplying each element of the array of numbers by 3;
  • reversing each element of the array of strings.

 

// Function forEach().
// Perform the specified operation for each element of the array.

// 1. Processing the array of numbers. Multiply each element of the array by 3
// 1.1. Array declaration
var A = new Array(2, 8, 3, 5, 4, 1)

// 1.2. Declare a function that multiplies the array[index] parameter by 3
function Mult3(value, index, array) {
  array[index] = value * 3
}

// 1.3. Create the new array and output it - call forEach()
A.forEach(Mult3);
console.log("A = " + A)

// 2. Processing the array of strings. Reverse each row of the array
// 2.1. Array declaration
var S = ["abc", "def", "jklm", "ghi"]

// 2.2. Reverse function - reverses array[index]
function Reverse(value, index, array) {
  var str = ""
  for (var i = 0; i < value.length; i++)
    str = value[i] + str
  array[index] = str
}

// 2.3. Apply the Reverse function on each row of array S
S.forEach(Reverse)
console.log(S)

console.log("Ok");

Result

A = 6,24,9,15,12,3
[ 'cba', 'fed', 'mlkj', 'ihg' ]
Ok

 

4. Method filter(). Get a new array whose elements satisfy a given condition

The filter() method allows you to select elements from the original array according to a condition and form a new array of these elements.

The use of the filter() method in a simplified form is as follows:

array1 = array2.filter(Func);

where

  • array2 is an object that is the original array;
  • array1 is an object that is the resulting array;
  • Func – name of a function that can take up to 3 parameters.

The Func() function is declared with the following syntax

function Func(value, index, array)
{
  // The body of a function that returns a boolean value (true or false)
  // ...
}

where

  • array – an array that is being filtered;
  • value – some value from the array. For value, the following equality holds: value==array[index];
  • index – position of value in the array. Having an index, you can filter the original array by index. For example, get a new array of elements placed at paired positions (0, 2, 4, …).

Thus, in the processing function, there is access to the array by the array[index] index or by the value.

If a single value parameter is enough to get the desired result, then the Func() function can look simplified:

function Func(value)
{
  // The body of a function that returns a boolean value (true or false)
  // ...
}

Example.

The example demonstrates getting a new array whose elements are in the range [5; 10].

// Function filter().
// Filters an array based on a given condition
// 1. Declare array of numbers
var A1 = [2, 8, 3, 5, 4, 1, 8, 3, 10];

// 2. A function that returns true if the number is between 5-10
function Range_5_10(value, index, array) {
  if ((array[index] >= 5) && (array[index] <= 10))
    return true;
  return false;
}

// 3. A function that does the same as the Range_5_10() function, only the value is checked
function Range_5_10_2(value)
{
  return (value >= 5) && (value <= 10);
}

// 4. Get a new array based on the Range_5_10() function
var A2 = A1.filter(Range_5_10)
console.log("A2 = " + A2)

// 5. Get a new array based on the Range_5_10_2() function.
var A3
A3 = A1.filter(Range_5_10_2)
console.log("A3 = " + A3)

console.log("Ok");

Result

A2 = 8,5,8,10
A3 = 8,5,8,10
Ok

 

5. Method map(). Get a new array that is formed based on the given transformation function

Using the map() method, you can get a new array that is formed based on the given transformation function. The method call looks like this

array2 = array1.map(Func)

where

  • array1 – source array whose elements are being converted. This array is also modified;
  • array2 – resulting array;
  • Func – a callback function that specifies an operation on an array element.

The declaration of the Func() function is as follows

function Func(value, index, array)
{
  // Actions that modify array[index]
  // ...
}

here

  • value – value of array[index] array element. Here the equality array[index]==value;
  • index – position of the value element;
  • array – directly processed array.

Example.

// Function map().
// Get a new array based on a given function

// 1. Processing the array of integers.
// Form the absolute value of each element of the array.
// 1.1. Declare the array of numbers and output it
var A1 = new Array(2, -8, -3, 5, -4, 1, 2, -3, 4, 4, -5, -2)
console.log("A1:")
console.log(A1)

// 1.2. Call the map() method with a function that returns the absolute value of a number
var A2 = A1.map(Math.abs) // use function from Math library
console.log("A2:")
console.log(A2)

// 2. Processing the array of real numbers.
// Form a new array in which the numbers of the previous array are multiplied by 2.
// 2.1. Declare the array of numbers and output it
var B1 = [ -2.8, -3.5, -1.4, -0.9905]
console.log("------------------------")
console.log("B1:")
console.log(B1)

// 2.1. Declare our function that will multiply an array element by 2
function Func(value, index, array) {
  array[index] = array[index] * 2
}

// 2.2. Call the map() method
B1.map(Func)
console.log("B1:")
console.log(B1)

console.log("Ok");

Результат

A1:
[
2, -8, -3, 5, -4,
1, 2, -3, 4, 4,
-5, -2
]
A2:
[
2, 8, 3, 5, 4,
1, 2, 3, 4, 4,
5, 2
]
------------------------
B1:
[ -2.8, -3.5, -1.4, -0.9905 ]
B1:
[ -5.6, -7, -2.8, -1.981 ]
Ok

 

6. Метод copyWithin(). Copy to the current array a fragment of a subarray that is part of the current array

The copyWithin() method is used to copy array fragments to another location in the same array. A method call can have a different number of parameters (from 1 to 3). Method returns the same array (this object).

Depending on the number of parameters, the following cases are distinguished.

Way 1. Method call with 1 parameter

array1.copyWithin(target)
array2 = array1.copyWithin(target)

where

  • array1 – the source array;
  • array2 – the array that is a reference to the resulting source array array1;
  • target – the position from which the insertion of a fragment of the same array begins. The fragment itself starts from the beginning of the array (from position 0).

Way 2. Method call with 2 parameters

array1.copyWithin(target, start)
array2 = array1.copyWithin(target, start)

where

  • array1 – the source array;
  • array2 – reference to array1;
  • target – insertion position of array1 array fragment starting from start position;
  • start – position from which the inserted fragment starts. The fragment size starts from position start to the end of the array.

Way 3. Method call with 3 parameters

array1.copyWithin(target, start, end)
array2 = array1.copyWithin(target, start, end)

where

  • array1 – the source array;
  • array2 – reference to array1;
  • target – insertion position of array1 array fragment starting from start position;
  • start, end – start and end positions of the inserted fragment. The last element to be inserted is the element at position end-1.

Example.

// Method copyWithin(). Copy part of the array to itself.

// The source array of numbers
var A1 = new Array( 0, 1, 2, 3, 4, 5, 6, 7 )

// 1. Calling a method with one parameter.
// Insert a fragment of the same array into the array A1 starting from position 3
var A2 = A1.copyWithin(3) // A2 = A1 = [0, 1, 2, 0, 1, 2, 3, 4 ]
console.log("A1 = " + A1)
console.log("A2 = " + A2)

// 2. Method call with 2 parameters
A1 = [0, 1, 2, 3, 4, 5, 6, 7]

// Insert into array A1 a fragment of the same array.
// Вставка начинается с позиции 2.
// the inserted fragment starts from position 3.
var A3 = A1.copyWithin(2, 3) // A3 = A1 = [0, 1, 3, 4, 5, 6, 7, 7]
console.log("A1 = " + A1)
console.log("A3 = " + A3)

// 3. Method call with 3 parameters
A1 = [0, 1, 2, 3, 4, 5, 6, 7]

// Insert into array A1 a fragment of the same array.
// The insert starts at position 2.
// The inserted fragment starts at position 3 and ends at position 6.
// Position 6 is not included in the fragment.
var A4 = A1.copyWithin(2, 3, 6) // A4 = A1 = [0, 1, 3, 4, 5, 5, 6, 7]
console.log("A1 = " + A1)
console.log("A4 = " + A4)

Result

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

 

7. Method splice(). Get a new array consisting of elements added to or removed from the given array.

The splice() method is designed to extract (remove) elements from the original array and replace them with new elements. The method returns an array containing the pulled out (removed) elements.

When using a method, it can be passed one, two, or three arguments. Possible cases of using the method are discussed below.

Way 1. The method takes one argument. In this case, the method usage is as follows

array2 = array1.splice(start)

where

  • array1 – processed source array;
  • array2 – the resulting array containing the elements extracted from the array1 array. This array contains all the elements of array1 from position start to the end of the array;
  • start – an integer that defines the position in array from which elements are removed. The start value starts at 0.

After calling the splice() method with 1 parameter, array1 is truncated. The removed elements are copied into array2.

Way 2. The method receives 2 arguments. In this case, the method usage is as follows

array2 = array1.splice(start, deleteCount)

where

  • array1 – initial array;
  • array2 – an array formed by copying deleteCount elements from the array1 array starting from the start position of the array1 array;
  • start – position in the array1 array, from which the elements are removed from the array1 array and the elements are copied to the array2 array;
  • deleteCount – number of elements from the array1 array to be deleted. The value of deleteCount also determines the number of elements copied from array1 to array2.

Way 3. The method receives 3 arguments. Here the method call could be like this

array2 = array1.splice(start, deleteCount, arrayItems)

where

  • array1, array2 – output and resulting arrays;
  • start – position in array1 from which data is removed and copied to array2. The start value starts at 0;
  • deleteCount – number of elements that are deleted from array1 and copied to array2;
  • arrayItems – an array of elements to be inserted in place of the removed elements from array1. All elements of the arrayItems array are inserted regardless of their number.

Example.

// Method splice().Get a new array consisting of elements that have been added and removed

// 1. Implementation of a method with 1 parameter
// 1.1. The original array of numbers
var A = new Array( 0, 1, 2, 3, 4, 5, 6, 7 )

// 1.2. Trim array A to position 3, get new array starting from position 3
var B = A.splice(3)

// 1.3. Display the result
console.log("A = " + A) // A = [ 0, 1, 2 ]
console.log("B = " + B) // B = [ 3, 4, 5, 6, 7 ]

// ---------------------------------

// 2. Method implementation with 2 parameters
// 2.1. The source array of numbers
A = [0, 1, 2, 3, 4, 5, 6, 7]

// 2.2. Extract elements [3, 4] from array A and write them to array B
B = A.splice(3, 2)

// 2.3. Display the result
console.log("A = " + A) // A = [ 0, 1, 2, 5, 6, 7 ]
console.log("B = " + B) // B = [ 3, 4 ]

// 3. Implementation of the method with 3 parameters.
// Here the elements retrieved from the original array are replaced with new elements
// 3.1. The source array of numbers
A = [0, 1, 2, 3, 4, 5, 6, 7]

// 3.2. Replace elements [3, 4] in array A from position 3
// to [8, 9, 10, 11], simultaneously copy 2 elements [3, 4] to array B
B = A.splice(3, 2, [8, 9, 10, 11])

// 3.3. Display the result
console.log("A = " + A) // A = [ 0, 1, 2, 8, 9, 10, 11, 5, 6, 7 ]
console.log("B = " + B) // B = [ 3, 4 ]

Result

A = 0,1,2
B = 3,4,5,6,7
A = 0,1,2,5,6,7
B = 3,4
A = 0,1,2,8,9,10,11,5,6,7
B = 3,4

 


Related topics