How to slice from an array of objects in js?
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);
}