I have an array of objects like this:
const books =[
{id: "1", name: "twilight", category: "Movies", price: 10},
{id: "2", name: "jaws", category: "Movies", price: 22},
{id: "3", name: "the shining", category: "Movies", price: 1},
{id: "4", name: "beers", category: "Movies", price: 10},
{id: "5", name: "apples", category: "Movies", price: 22},
{id: "6", name: "mono", category: "Movies", price: 1}
]
Trying to slice the first 2, then second 2 etc.
How can I slice by 2 books at the time?
Array.prototype.slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.
splice() JS Array Method. The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.
JavaScript slice() Method: Array ObjectThe slice() method is used to extract a section of an array. The method returns a new array and it does not change the original array, selected elements of the original array are copied into a new array.
The slice() method can be used to create a copy of an array or return a portion of an array. It is important to note that the slice() method does not alter the original array but instead creates a shallow copy. Let's take a look at some examples to better understand how the slice() method works.
Array.prototype.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
Try with for
loop with a increment of 2 in each iteration. Pass the current value of i
as the start position and i+2
as the end position as the method parameter:
const books =[
{id: "1", name: "twilight", category: "Movies", price: 10},
{id: "2", name: "jaws", category: "Movies", price: 22},
{id: "3", name: "the shining", category: "Movies", price: 1},
{id: "4", name: "beers", category: "Movies", price: 10},
{id: "5", name: "apples", category: "Movies", price: 22},
{id: "6", name: "mono", category: "Movies", price: 1}
]
for(var i=0; i<books.length; i+=2){
var sliced = books.slice(i, i+2);
console.log(sliced);
}
You can use the slice function passing the number of books to slice (i.e. 2):
let slicedBooks = []
for(var i = 0;i < books.length;i+= 2){
let part_slice = books.slice(i, 2 + i);
slicedBooks.push(part_slice);
console.log(part_slice);
}
console.log(slicedBooks);
Be careful slice does not update books array, but returns a new array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With