How can i do skip and limit array of object using javascript?

Solution 1:

products.slice(index,index+count)

would be the answer

Solution 2:

Make sure you have your data ready and call the Array.prototype.slice method as shown in the code snippet below. The method returns a shallow copy of array values within the specified start and end parameter; The first parameter is where to start while the last parameter is where to end.

The start is defined by the skip variable while the end is defined by the sum of both skip and limit variables.

Array values are generally accessed using their index. Arrays indexes start from 0 upwards, so the slice methods start counting from zero to the provided start and end params and so when we do the sum of skip and limit variable we get to ensure we have the expected number of items in the result.

// Define the data you want to skip and limit

let products = [
  {
    id: "1",
    inventory: 5,
    unit_price: 45.99
  },
  {
    id: "2",
    inventory: 10,
    unit_price: 123.75
  },
  {
    id: "3",
    inventory: 2,
    unit_price: 399.50
  },{
    id: "4",
    inventory: 5,
    unit_price: 45.99
  },
  {
    id: "5",
    inventory: 10,
    unit_price: 123.75
  },
  {
    id: "6",
    inventory: 2,
    unit_price: 399.50
  },
  {
    id: "7",
    inventory: 10,
    unit_price: 123.75
  },
  {
    id: "8",
    inventory: 2,
    unit_price: 399.50
  },{
    id: "9",
    inventory: 5,
    unit_price: 45.99
  },
  {
    id: "10",
    inventory: 10,
    unit_price: 123.75
  },
  {
    id: "11",
    inventory: 2,
    unit_price: 399.50
  }
];

/* define the skip and limit parameters, so skip variable here is the number of items to skip while the limit variable is the number of items you expect in the result*/

let skip = 2;
let limit = 5;

/* Below we used the Array.prototype.slice method you can search on google if you don't know what array prototypes are, the slice method takes two params, first the start i.e where to start from, and second, the end i.e where to end, so skip variable is telling slice method where to start while the sum of skip and limit variables is provided as, where to end the slice method, this is done so to ensure the result is the limit provided. To learn more read about Arrays in javascript*/

let result =  products.slice(skip, skip+limit);

console.log(result)

Solution 3:

const limit = 5, index = 2;
console.log(products.slice(index, limit + index))