Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
How do you split an array into array pairs in JavaScript?

I want to split an array into pairs of arrays.

var arr = [2, 3, 4, 5, 6, 4, 3, 5, 5]

would be

var newarr = [
    [2, 3],
    [4, 5],
    [6, 4],
    [3, 5],
    [5]
]
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can use js reduce

initialArray.reduce(function(result, value, index, array) {
  if (index % 2 === 0)
    result.push(array.slice(index, index + 2));
  return result;
}, []);
over 4 years ago · Santiago Trujillo Report

0

Lodash has a method for this: https://lodash.com/docs/4.17.10#chunk

_.chunk([2,3,4,5,6,4,3,5,5], 2); // => [[2,3],[4,5],[6,4],[3,5],[5]]

over 4 years ago · Santiago Trujillo Report

0

There's no pre-baked function to do that, but here's a simple solution:

var splitPairs = function(arr) {
    var pairs = [];
    for (var i=0 ; i<arr.length ; i+=2) {
        if (arr[i+1] !== undefined) {
            pairs.push ([arr[i], arr[i+1]]);
        } else {
            pairs.push ([arr[i]]);
        }
    }
    return pairs;
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!