14

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?

3
  • can little bit more like what should be your desire output.. Commented Oct 31, 2018 at 4:15
  • Slice first 2 items then second couple etc Commented Oct 31, 2018 at 4:16
  • Any reason for not using books.slice(0, 2)? that would get you the first 2, then you would just have to keep increasing the indexes to get the remaining parts Commented Oct 31, 2018 at 4:16

8 Answers 8

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

that slice would return everything on the array starting from index 2, not exactly what he's looking for, which is getting elements in groups of two
2

You can use try this slice method

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

Comments

1

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!

3 Comments

@bierhier So the chunked result have all the couples, for first couple res[0] for second couple res[1] and so on... basically you can iterate (as I mentioned in answer) the res and get all the couples one by one.
Not everyone wants to (or can) use lodash, which is an abstraction. The language itself can do this and it would be more helpful to see that, rather than a shortcut.
@TsarBomba that can be also done. But it's not about everyone it's specific about OP's case as he have tagged lodash in the question.
1

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

Comments

0

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

Comments

0

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)]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.