How to Split an Array Into Chunks in JavaScript
- Split an Array Using the slice() Method in JavaScript
- Separating Every Element of an Array Using the slice() Method and forEach Loop in JavaScript
In JavaScript, playing with arrays and performing various operations on the arrays, whether it’s the insertion, deletion, or data manipulation inside an array, are very common things that every programmer should know.
The JavaScript language makes our life much easier by providing us with various awesome built-in functions that allow us to play and modify with the array data structure. One such method we will discuss in this article is the slice() function. With this method, we can easily divide or split an entire array into various chunks.
Split an Array Using the slice() Method in JavaScript
The slice() method is used to slice or divide an array into smaller chunks. This function takes two parameters as input, start and end . The start represents the starting index from where you want to begin slicing the array, and the end represents at which index you want to stop slicing or dividing.
In this process, note that the slicing will stop one index before the end index you specified. For example, if you have defined end as 5 , the method will stop slicing one index before, i.e., at index 4 .
After the slicing is done, the original array remains unchanged. Modern browsers support this method.
In the code example below, we have an array called numbersArr , which is of the integers type. We can pass the start and end parameters to split or divide this array. Here, we have passed 2 and 5 as the start and end parameters.
let numbersArr = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(numbersArr.slice(2, 5)); console.log('Original Array: ', numbersArr);
[3, 4, 5] Original Array: [1, 2, 3, 4, 5, 6, 7, 8]
Since at index 2 , we have the element number 3 and one index before index 5 , we have an element number 5 . So, the slice() method will split this array, and we will get the output as [3, 4, 5] . As already discussed, the original array remains unchanged, and so if we print the numbersArr array, we will get the entire array with all the elements present as the output.
Both parameters start and end are optional. If you don’t specify the start position, then the slice() method will take 0 as its default value. If you don’t specify the end position, it will go to the last element of the array with the help of the array.length method.
Separating Every Element of an Array Using the slice() Method and forEach Loop in JavaScript
To divide or split all the array elements, we can use both the slice() method and the for loop. You can also use a for loop here — it’s not an issue. Additionally, we also have the same numbersArr array. Whenever we use a forEach loop on an array, we have to pass call-back functions, which will provide us with two things: first is the element of an array itself, and the second is its index. At every iteration, we will go through each element of an array and get its respective index.
let numbersArr = [1, 2, 3, 4, 5, 6, 7, 8]; numbersArr.forEach((value, index) => console.log(numbersArr.slice(index, index + 1)); >);
[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] [ 7 ] [ 8 ]
We will pass that index value as a start parameter and index+1 as the end parameter to the slice() method. So, for example, if the index value is 0 then index + 1 becomes 0 + 1 = 1 . And as we know that the slice() method will stop one element before the end index, we want to split every element of the array here; therefore, we will initially pass split(0,1) so that the method will take one element at a time from the array and will print it.
In the second iteration, it will be split(1,2) . The third iteration will be split(2,3) and so on until it reaches the end of the array.
This way, we will be able to split every element of an array into various chunks. If you want to access these individual elements later in your code, you can also store these elements by creating separate arrays for every element depending upon your needs.
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.
Related Article — JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript
How to Split an Array Into Chunks in JavaScript
- Split an Array Using the slice() Method in JavaScript
- Separating Every Element of an Array Using the slice() Method and forEach Loop in JavaScript
In JavaScript, playing with arrays and performing various operations on the arrays, whether it’s the insertion, deletion, or data manipulation inside an array, are very common things that every programmer should know.
The JavaScript language makes our life much easier by providing us with various awesome built-in functions that allow us to play and modify with the array data structure. One such method we will discuss in this article is the slice() function. With this method, we can easily divide or split an entire array into various chunks.
Split an Array Using the slice() Method in JavaScript
The slice() method is used to slice or divide an array into smaller chunks. This function takes two parameters as input, start and end . The start represents the starting index from where you want to begin slicing the array, and the end represents at which index you want to stop slicing or dividing.
In this process, note that the slicing will stop one index before the end index you specified. For example, if you have defined end as 5 , the method will stop slicing one index before, i.e., at index 4 .
After the slicing is done, the original array remains unchanged. Modern browsers support this method.
In the code example below, we have an array called numbersArr , which is of the integers type. We can pass the start and end parameters to split or divide this array. Here, we have passed 2 and 5 as the start and end parameters.
let numbersArr = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(numbersArr.slice(2, 5)); console.log('Original Array: ', numbersArr);
[3, 4, 5] Original Array: [1, 2, 3, 4, 5, 6, 7, 8]
Since at index 2 , we have the element number 3 and one index before index 5 , we have an element number 5 . So, the slice() method will split this array, and we will get the output as [3, 4, 5] . As already discussed, the original array remains unchanged, and so if we print the numbersArr array, we will get the entire array with all the elements present as the output.
Both parameters start and end are optional. If you don’t specify the start position, then the slice() method will take 0 as its default value. If you don’t specify the end position, it will go to the last element of the array with the help of the array.length method.
Separating Every Element of an Array Using the slice() Method and forEach Loop in JavaScript
To divide or split all the array elements, we can use both the slice() method and the for loop. You can also use a for loop here — it’s not an issue. Additionally, we also have the same numbersArr array. Whenever we use a forEach loop on an array, we have to pass call-back functions, which will provide us with two things: first is the element of an array itself, and the second is its index. At every iteration, we will go through each element of an array and get its respective index.
let numbersArr = [1, 2, 3, 4, 5, 6, 7, 8]; numbersArr.forEach((value, index) => console.log(numbersArr.slice(index, index + 1)); >);
[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ] [ 6 ] [ 7 ] [ 8 ]
We will pass that index value as a start parameter and index+1 as the end parameter to the slice() method. So, for example, if the index value is 0 then index + 1 becomes 0 + 1 = 1 . And as we know that the slice() method will stop one element before the end index, we want to split every element of the array here; therefore, we will initially pass split(0,1) so that the method will take one element at a time from the array and will print it.
In the second iteration, it will be split(1,2) . The third iteration will be split(2,3) and so on until it reaches the end of the array.
This way, we will be able to split every element of an array into various chunks. If you want to access these individual elements later in your code, you can also store these elements by creating separate arrays for every element depending upon your needs.
Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.
Related Article — JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript
Array.prototype.flat()
This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020 .
Метод flat() возвращает новый массив, в котором все элементы вложенных подмассивов были рекурсивно «подняты» на указанный уровень depth.
Синтаксис
var newArray = arr.flat(depth);
Параметры
depth Необязательный
На сколько уровней вложенности уменьшается мерность исходного массива. По умолчанию 1.
Возвращаемое значение
Новый массив с объединёнными в него подмассивами.
Примеры
Упрощение вложенных массивов
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Упрощение и «дырки» в массивах
Метод flat удаляет пустые слоты из массива:
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
Альтернативы
reduce и concat
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // В одномерный массив arr1.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4] //или const flatSingle = (arr) => [].concat(. arr);
// Для развёртывания многомерных массивов используем рекурсию, reduce и concat const arr = [1, 2, [3, 4, [5, 6]]]; function flatDeep(arr, d = 1) return d > 0 ? arr.reduce( (acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [], ) : arr.slice(); > flatDeep(arr, Infinity); // [1, 2, 3, 4, 5, 6]
//не рекурсивное упрощение с использованием стэка var arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]]; function flatten(input) const stack = [. input]; const res = []; while (stack.length) // забираем последнее значение const next = stack.pop(); if (Array.isArray(next)) // добавляем к массиву элементы не модифицируя исходное значение stack.push(. next); > else res.push(next); > > //разворачиваем массив, чтобы восстановить порядок элементов return res.reverse(); > flatten(arr1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
//рекурсивно упрощаем массив function flatten(array) var flattend = []; (function flat(array) array.forEach(function (el) if (Array.isArray(el)) flat(el); else flattend.push(el); >); >)(array); return flattend; >
Спецификации
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.flat |
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
- Array.prototype.flatMap()
- Array.prototype.map()
- Array.prototype.reduce()
- Array.prototype.concat()
Разделить массив на подмассивы [0,1,2,3,4,5,6,7,8,9] -> [[0,1],[2,3,4],[5,6], [7,8,9]]?
Условия по сохранению целостности оригинального массива нет, если есть — можно скопировать массив перед сплайсами, а так — вот:
let arr = [0,1,2,3,4,5,6,7,8,9]; let result = []; while (arr.length) result.push(arr.splice(0, 2), arr.splice(0, 3)) console.log(JSON.stringify(result));
let arr = [0,1,2,3,4,5,6,7,8,9]; let result = [2,3,2,3].map(i => arr.splice(0, i)); console.log(JSON.stringify(result));
PS: это конечно не универсально
Отслеживать
ответ дан 30 окт 2019 в 11:59
Stranger in the Q Stranger in the Q
56.1k 10 10 золотых знаков 83 83 серебряных знака 136 136 бронзовых знаков
Вы на личном опыте этому всему научились, или есть какая-то книжка с секретными знаниями?)) Например, додуматься в push добавить два таких аргумента)
30 окт 2019 в 12:05
@OPTIMUSPRIME это ладно. А про второе я даже пару минут думал, но плюнул 🙂 Это только опыт, причем в конкретном языке. ТО что работает в js — совершенно не одно и тоже, что в python, например
30 окт 2019 в 12:07
@OPTIMUSPRIME я тоже так думаю это не человек под этим профилем какой то высший ИИ стоит 😀 .Ну то что он пишет то что творит с кодом это меня всегда удивляет и в каждом его ответе есть что то новое лично для меня ))
30 окт 2019 в 12:09
@OPTIMUSPRIME я просто много пишу всякую ерунду, вот и натаскался, книжки определенно есть, но всякие приемы я подсматривал и подсматриваю на всяких там codepen итд, ведь хорошо же, когда кода мало, я к этому пытаюсь стремиться в своих поделках (я не про промышленный код а про ответы тут и тот же codepen)
30 окт 2019 в 12:21
@OPTIMUSPRIME но в целом — геймдев и компьютерная графика хорошо вправляет мозги, я вот с тех пор как этим занимаюсь, на тот код который писал до этого и задачи, которые решал- смотреть не могу, наверное так всегда, когда найдешь область, которая действительно по душе