В этом отрывке мы в основном сосредоточимся на этих встроенных функциях массивов и нескольких вариантах их использования.

  1. уменьшать()

Выполните функцию для каждого элемента в массиве и аккумулируйте их, чтобы получить окончательный результат.

Example 1
let numbers = [1, 2, 3, 4, 5];
let result = numbers.reduce(sum);
//total - the value of last result
//At the beginning, the total is 1 - 1st element in array, 
//and num is 2 - 2nd element array
//Then the value of total will be 1 + 2 = 3, 
//and num will be 3 - 3rd element array
//Then the value of total will be 1 + 2 + 3 = 6, 
//and num will be 4 - 4th element array
//Then the value of total will be 1 + 2 + 3 + 4 = 10, 
//and num will be 5 - 5th element array
//Then the value of total will be 1 + 2 + 3 + 4 + 5 = 15,
//becoz this array got 5 elements only, so 15 will be the final //answer
function sum(total, num) {
  return total + num;
}
console.log(result);
//output 15, becoz 1 + 2 + 3 + 4 + 5

Другой пример

let numbers = [100, 40, 30, 20, 10];
let result = numbers.reduce(minus);
function minus(total, num) {
  return total - num;
}
console.log(result);
//output 0, becoz 100 - 40 - 30 - 20 - 10

Другой пример (с необязательным параметром для начального значения)

let numbers = [100, 40, 30, 20, 10];
//300 is the initial value we given, 
//optional parameter of reduce function
let result = numbers.reduce(minus, 300);
//total - the value of last result
//At the beginning, the total is the initial value we provide - 300
//and num is 100 - 2nd element array
//Then the value of total will be 300 - 100 = 200, 
//and num will be 30 - 3rd element array
//Then the value of total will be 300 - 100 - 40 = 160, 
//and num will be 20 - 4th element array
//Then the value of total will be 300 - 100 - 40 - 20 = 110, 
//and num will be 10 - 5th element array
//Then the value of total will be 300 - 100 - 40 - 20 - 10 = 100,
//becoz this array got 5 elements only, so 100 will be the final //answer
function minus(total, num) {
  return total - num;
}
console.log(result);
//output 100, becoz 300 - 100 - 40 - 30 - 20 - 10

2. фильтр()

Возвращает новый массив, который включает те элементы, которые переданы (возвращают true) функции фильтра

let numbers = [100, 40, 30, 20, 10];
let result = numbers.filter(checking);
//filter function, check whether number smaller than 100
function checking(num) {
  return num < 100;
}
console.log(result);
//[40, 30, 20, 10]

Другой пример

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
let result = fruits.filter(checking);
//check whether each fruit contains character 'i'
function checking(fruit) {
  return fruit.includes('i');
}
console.log(result);
//['kiwi']
//only 'kiwi' contains 'i'

3. сращивание ()

Добавить или удалить элемент в существующем массиве и вернуть новый массив, содержащий удаленный элемент

Пример удаления элемента — из первого элемента

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//2 parameters, the first one is which element by index to remove
//the second parameter is how many element to be remove
//In this example, start from index 0 to remove 1 element
let removedElements = fruits.splice(0, 1);
console.log(fruits);
//['orange', 'banana', 'kiwi']
console.log(removedElements);
//['apple']

Другой пример удаления элемента — из последнего элемента

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//Let say we want to started from the last element, we can use //negative number in the first parameter
//the last element is -1, vice versa
//And the direction (of removing) is same as positive number //parameter
//So, 'banana' and 'kiwi' will be remove instead of 'banana' and //'orange'
let removedElements = fruits.splice(-2, 2);
console.log(fruits);
//['apple', 'orange']
//-2 means the second last element, that means removed 'banana'
console.log(removedElements);
//['banana', 'kiwi']

Добавить элемент

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//first 0, start from index 0
//second 0, remove 0 element
//'mango' - the new element we going to add, it will add to the //first element (according to first param)
fruits.splice(0, 0, 'mango');
console.log(fruits);
//['mango', 'apple', 'orange', 'banana', 'kiwi']

Добавить и удалить элемент

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//first 1, start from index 1 (second element)
//second 1, remove one element
//'mango', 'pineapple' - the new element we going to add
fruits.splice(1, 1, 'mango', pineapple);
console.log(fruits);
//['apple', 'banana', 'kiwi', 'orange', 'banana', 'kiwi']

4. срез ()

Скопировать выбранные элементы по начальному и конечному индексу в новый массив

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//first parameter, start from index 1 (second element)
//second parameter, end at index 3(fourth element), but not //including it
var someFruits = fruits.slice(1, 3);
console.log(someFruits);
//['orange', 'banana']

Другой пример с использованием отрицательного индекса

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//first parameter, start from index -3 (second element)
//second parameter, end at index 3(fourth element), but not //including it
//And the direction (of removing) is same as positive number //parameter
//So the second parameter always larger than the first parameter
//In this case, the last 3rd element is 'orange' and end at the last //2nd element (but not including it), so only 'orange' will be //copy
var someFruits = fruits.slice(-3, -2);
console.log(someFruits);
//['orange']

Другой пример без параметра

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
//by default, if we left empty, 1st parameter will be 0
//for the 2nd parameter, if we left empty, will be the end of array
//that means in this case we will copy everything from the array
var someFruits = fruits.slice();
console.log(someFruits);
//['apple', 'orange', 'banana', 'kiwi']

5. конкат()

Добавьте элементы других массивов в конец и верните новый результат в новом массиве.

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
let snacks = ['chips', 'candy', 'chocolate', 'mints'];
//always returns new array, existing arrays not affected
let food = fruits.concat(snacks);
console.log(food);
//['apple', 'orange', 'banana', 'kiwi', 'chips', 'candy', 'chocolate', 'mints']

6. найти()

Аналогично filter(), но он прекращает поиск, как только найден первый результат.

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
let result = fruits.find(findFunc);
//filter function, check whether number smaller than 100
function findFunc(fruit) {
  return fruit.includes('a');
}
console.log(result);
//apple
//apple, orange, banana also contain 'a', but since 'apple' locate //at the first index, so return 'apple'

7. найтиИндекс()

Аналогично find(), поиск по каждому элементу массива и прекращение поиска после первого найденного возврата, но вместо значения возвращается номер индекса.

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
let result = fruits.findIndex(findFunc);
//filter function, check whether number smaller than 100
function findFunc(fruit) {
  return fruit.includes('a');
}
console.log(result);
//0
//As apple located at the first index

8. Объект.назначить()

Скопируйте свойства одного или нескольких объектов в другой объект. Новый массив не будет возвращен, только добавление/перезапись целевого объекта (1-й параметр)

const fruitsCount = { kiwi: 1, banana: 2 };
const snacksCount = { candy: 4, chocolate: 9 };
//1st parameter is the target object, all properties in 2nd and
//other parameter will be copy to the 1st parameter
//In this case, the properties from snacksCount will be copy to //fruitsCount
Object.assign(fruitsCount, snacksCount);
console.log(fruitsCount);
// {kiwi: 1, banana: 2, candy: 4, chocolate: 9}
console.log(snacksCount);
// {candy: 4, chocolate: 9}

Другой пример

const fruitsCount = { kiwi: 1, banana: 2 };
const snacksCount = { candy: 4, chocolate: 9, banana: 3 };
const vegeCount = { eggPlant: 7, banana: 5};
//1st parameter is the target object, all properties in 2nd and
//other parameter will be copy to the 1st parameter
//In this case, the properties from snacksCount and vegeCount will //be copy to fruitsCount
//If multi parameter got the same properties ('banana' in this //case), then the properties from "later" parameter will be apply
//In this case, 'banana: 5' from vegeCount will apply instead of //'banana: 3' from snacksCount
Object.assign(fruitsCount, snacksCount, vegeCount);
console.log(fruitsCount);
{kiwi: 1, banana: 5, candy: 4, chocolate: 9, eggPlant: 7}
console.log(snacksCount);
// {candy: 4, chocolate: 9, banana: 3}
console.log(vegeCount);
// {eggPlant: 7, banana: 5}

9. ИндексОф

Найдите индекс в массиве по значению элемента, если более одного элемента массива имеют одинаковое значение, он вернет индекс первого элемента.

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
let index = fruits.indexOf('orange');
console.log(index);
//return 1

10. толчок

Добавить новый элемент в последний индекс существующего массива

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
fruits.push('cherry');
console.log(fruits);
//['apple', 'orange', 'banana', 'kiwi', 'cherry']

11. поп

Удалить последний элемент из существующего массива

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
fruits.pop();
console.log(fruits);
//['apple', 'orange', 'banana']

12. сдвиг

Удалить первый элемент из существующего массива

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
fruits.shift();
console.log(fruits);
//['orange', 'banana', 'kiwi']

13. переключить

Добавить новый элемент в первый массив

let fruits = ['apple', 'orange', 'banana', 'kiwi'];
fruits.shift('cherry');
console.log(fruits);
//['cherry', 'apple', 'orange', 'banana', 'kiwi']

Некоторые распространенные варианты использования

  1. Удаление повторяющегося элемента

По фильтру()

let duplicate_array = ['apple', 'orange', 'orange', 'banana', 'banana', 'kiwi', 'banana'];
let filtered_array = duplicate_array.filter(
function(element, index) {
return index === duplicate_array.indexOf(element); })
console.log(filtered_array);
//['apple', 'orange', 'banana', 'kiwi']

По Array.from() и Set

let duplicate_array = ['apple', 'orange', 'orange', 'banana', 'banana', 'kiwi', 'banana'];
//Automatically removes duplicate elements
const set = new Set(duplicate_array);
let filtered_array = Array.from(set);
console.log(filtered_array);
//['apple', 'orange', 'banana', 'kiwi']

2. Поиск повторяющихся элементов

По уменьшению () и indexOf ()

let duplicate_array = ['apple', 'orange', 'orange', 'banana', 'banana', 'kiwi', 'banana'];
function sum(list, element, index) {
//just keep in mind that the default index is 1, becoz the total is //the value of 1st element. However, if we added the optional //parameter - initial value, the index will be 0 (the 1st index in //array)
let duplicated = index !== duplicate_array.indexOf(element);
if (duplicated && list.indexOf(element) < 0)    {
        list[list.length] = element
    }
return list;    
}
let duplicated_list = duplicate_array.reduce(sum, []);
console.log(duplicated_list);
//['orange', 'banana']

3. Копирование массива с вложенным массивом

Поскольку управление состоянием в React.JS и Redux всегда требует неизменного значения состояния, поэтому вместо обновления текущего объекта мы часто создаем новый и копируем значение, чтобы соответствовать стандарту. (По причине неизменяемости см. другой отрывок)

Подробнее об обновлении состояния Redux неизменяемым образомhttps://redux.js.org/recipes/structuring-reducers/immutable-update-patterns

const fruits = ['kiwi', 'banana'];
const snacks = ['candy', 'chocolate'];
const drink = ['beer', 'coke'];
let food = [fruits, snacks];
let all = [food, drink];
//only copy the reference address
let copy_all = all
all.push('new_item');
//both 'all' and 'copy_all' show the new value, that means we copied //the object reference only
console.log(all);
console.log(copy_all);
copy_all = [..all];
all.push('new_item2');
//array 'all' reflects new value, array 'copy_all' doesn't, that //means we copied the value, not reference
console.log(all);
console.log(copy_all);
//try to add new value 'new_item3' to the nested array
all[0].push('new_item3');
//both 'all' and 'copy_all' show the new value, that means for the //nested array we copied the object reference only
//we realize that each array/ nested array have to be copied //'manually'
//the final result
copy_all = [[[...all[0][0]], [...all[0][1]]], [...all[1]]];
console.log(copy_all);

Следующая встроенная функция массива будет редактировать существующий массив, поэтому вы можете не использовать их при редактировании состояния React.JS/Redux.

splice()
Object.assign()
push()
pop()
shift()
unshift()