How to slice from an array of objects in js?

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?

Answers:

Answer

Since you are using lodash, you can use _.chunk (lodash#chunk) to populate a array of array containing first 2, then second 2, and so on...

_.chunk(books, 2)

Here is an working example:

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}
  ],
  res = _.chunk(books, 2);
  
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Now, you have the chunked array, iterate and take one by one item to get what exactly you need!

Answer

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);
}

Answer

Use a sliding widow iterator which sides over a set of 2 books at a time

function two_at_a_time(arr, func){
    for(var i=0; i < arr.length - 1; i++){
        func(arr[i], arr[i + 1]);
    }
}

two_at_a_time(books, function(current, next){
    console.log(current, next);
});
Answer

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.

Answer

You can use try this slice method

return books.slice(0,2).map((book, i) => {
      return;
    });
Answer

You can use a for loop with 2 steps at a time for the index, and slice based on the current index.

for (var i=0; i<books.length; i+=2) {
    console.log(books.slice(i, i+2));
}

This also works even if there are odd number of books

Answer

You can also try this code snippet -

var chunckedArray = function(books, chunkCount){
     var chunks = [];
     while(books.length){
         chunks.push(books.splice(0, chunkCount));
     }
     return chunks;
};

chunckedArray(books, 2); // [Array(2), Array(2), Array(2)]
Answer

100% equal to php

function array_slice (arr, offst, lgth, preserveKeys) { // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/array_slice/
  // original by: Brett Zamir (https://brett-zamir.me)
  //    input by: Brett Zamir (https://brett-zamir.me)
  // bugfixed by: Kevin van Zonneveld (https://kvz.io)
  //      note 1: Relies on is_int because !isNaN accepts floats
  //   example 1: array_slice(["a", "b", "c", "d", "e"], 2, -1)
  //   returns 1: [ 'c', 'd' ]
  //   example 2: array_slice(["a", "b", "c", "d", "e"], 2, -1, true)
  //   returns 2: {2: 'c', 3: 'd'}




  var key = ''

  if (Object.prototype.toString.call(arr) !== '[object Array]' || (preserveKeys && offst !== 0)) {
    // Assoc. array as input or if required as output
    var lgt = 0
    var newAssoc = {}
    for (key in arr) {
      lgt += 1
      newAssoc[key] = arr[key]
    }
    arr = newAssoc

    offst = (offst < 0) ? lgt + offst : offst
    lgth = lgth === undefined ? lgt : (lgth < 0) ? lgt + lgth - offst : lgth

    var assoc = {}
    var start = false
    var it = -1
    var arrlgth = 0
    var noPkIdx = 0

    for (key in arr) {
      ++it
      if (arrlgth >= lgth) {
        break
      }
      if (it === offst) {
        start = true
      }
      if (!start) {
        continue
      }++arrlgth
      if (isInt(key) && !preserveKeys) {
        assoc[noPkIdx++] = arr[key]
      } else {
        assoc[key] = arr[key]
      }
    }
    // Make as array-like object (though length will not be dynamic)
    // assoc.length = arrlgth;
    return assoc
  }

  if (lgth === undefined) {
    return arr.slice(offst)
  } else if (lgth >= 0) {
    return arr.slice(offst, offst + lgth)
  } else {
    return arr.slice(offst, lgth)
  }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.