Home > Software design >  How to create new array with begins and limit numbers in Javascript
How to create new array with begins and limit numbers in Javascript

Time:10-10

I want to create with transforming old array.

arr1 = [ 4,  26,  40,  53,  58,  68,  73,  86, 91, 114, 119, 132, 137, 147, 152, 165, 170, 183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289, 301, 306, 318, 323 ]

I want to create like

newArr = [[4,5,6,7,8,9,10 ..., 24,25], [26,27,28 ..., 39], [40,...,52], ...]

As you see in arr1, the number is the beginning, and the next item - 1 is the last number. How I can do like this. The last number is 325 in arr1 I tried chunk_array, but it does not work.

CodePudding user response:

You could use map and Array.from and then get all except the last one with slice(0, -1).

const arr = [4, 26, 40, 53, 58, 68, 73, 86, 91, 114, 119, 132, 137, 147, 152, 165, 170, 183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289, 301, 306, 318, 323]
const result = arr.map((e, i) => Array.from(Array((arr[i   1] || e) - e), (_, j) => e   j)).slice(0, -1)
console.log(result)

CodePudding user response:

1) You can use map and Array.from to achieve the desired result

const arr1 = [
  4, 26, 40, 53, 58, 68, 73, 86, 91, 114, 119, 132, 137, 147, 152, 165, 170,
  183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289,
  301, 306, 318, 323,
];

const result = arr1.map((el, i, src) => {
  const start = el, end = src[i   1];
  return Array.from({ length: end - start }, (_, i) => i   start);
});

result.pop();
console.log(result);

2) You can also do as

const arr1 = [
  4, 26, 40, 53, 58, 68, 73, 86, 91, 114, 119, 132, 137, 147, 152, 165, 170,
  183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289,
  301, 306, 318, 323,
];

const result = arr1.map((el, i, src) => {
  const start = el, end = src[i   1] ?? start;
  return Array(end - start)
    .fill(0)
    .map((_, i) => i   start);
});

result.pop();
console.log(result);

3) You can also use reduce here:

const arr1 = [
  4, 26, 40, 53, 58, 68, 73, 86, 91, 114, 119, 132, 137, 147, 152, 165, 170,
  183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289,
  301, 306, 318, 323,
];

const result = arr1.reduce((acc, start, i, src) => {
  const temp = Array((src[i   1] ?? start) - start)
    .fill(0)
    .map((_, i) => i   start);
  if (temp.length) acc.push(temp);
  return acc;
}, []);

console.log(result);

CodePudding user response:

const data = [ 4,  26,  40,  53,  58,  68,  73,  86, 91, 114, 119, 132, 137, 147, 152, 165, 170, 183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289, 301, 306, 318, 323 ]

const result = data.map((n, index, array) => Array.from({ length: ( array[index 1] || n 1 ) - n }, (_, i) => i n));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related