V
V
vechnomolodoy2017-08-14 03:18:58
PHP
vechnomolodoy, 2017-08-14 03:18:58

How to split an array into n number of elements?

There is an array

const = [
      {
          id: 1,
          title: Title1
      },
      {
          id: n,
          title: Titlen
      }
]

You need to split it into a certain number, for example, into 3 arrays and write it to a new array

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Valentin, 2019-04-04
@siroper

$url = preg_replace('/page_[0-9]+\//', '', '/catalog/masla-zhidkosti-i-smazki/page_2/');

G
gleendo, 2017-08-14
@evgeniy8705

// так?
const arr = [{
  id: 1,
  title: "title1"
}, {
  id: 2,
  title: "title2"
}];

let result = arr.map(item => Array.of(item));

console.log(result); // 

I
Ivan GiBSON, 2017-08-14
@gibson_dev

The implementation of what is called on the forehead, but it should be a shame for the fact that you don’t want to think about it. Or are you the breed of StackOverflow programmers?

function split(input, chunkSize){
  if(!chunkSize || !Array.isArray(input)){
    return input;
  }
  
  const result = [];
  
  for(let i = 0; i < input.length; i += chunkSize){
  	result.push(input.slice(i, chunkSize + i));
  }
  
  return result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question