0

I have an array called targetPercentage.

targetPercentage = [0,33,77,132]

How do I bin it into chunks of length 2 but include the previous value? If possible could also make it into a Javascript object array with its respective properties.

Example output :

[0,33]
[33,77]
[77,132]

Example output by making it into an array of objects :

thresholds : [ {from:0,to:33},{from:33,to:77},{from:77,to:132} ] 

Something similar to this question but inclusive of the previous value.

Syed Ariff
  • 722
  • 2
  • 8
  • 26

4 Answers4

1

You can create an array from scratch with Array.from and access the ith element as well as the i + 1th element on every iteration to create the objects:

const targetPercentage = [0,33,77,132];
const result = Array.from(
  { length: targetPercentage.length - 1 },
  (_, i) => ({ from: targetPercentage[i], to: targetPercentage[i + 1] })
);
console.log(result);

Or if you want an array of arrays instead:

(_, i) => ([ targetPercentage[i], targetPercentage[i + 1] ])
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0
const targetPercentage = [0, 33, 77, 132]

const thresholds = []
for (let i = 0; i < targetPercentage.length - 1; i++) {
let range = {
  from: targetPercentage[i],
  to: targetPercentage[i + 1]
 }
 thresholds.push(range) 
}
adam.k
  • 622
  • 3
  • 15
  • Although this code might (or might not) solve the problem, a good answer should explain what the code does and how it solves the problem. – BDL Oct 02 '18 at 08:09
0

array function-slice(initial,count) -slices the given array into 3 chunks of 2 elements each.

temp array will have[0,33],[33,77],[77,132]

 var i,j,temparray,chunk = 2;
        result=[];for (i=0,j=targetPercentage.length; i<j-1; i++) {
            temparray = targetPercentage.slice(i,i+chunk);
           result.push({from:temparray[0],to:temparray[1]});
        }
        console.log(result);
Monica Acha
  • 1,076
  • 9
  • 16
  • 1
    Although this code might (or might not) solve the problem, a good answer should explain what the code does and how it solves the problem. – BDL Oct 02 '18 at 08:08
0

You can try this out:

function binData(array) {
  let result = []

  for (let i=0; i<array.length-1; i++) {
    result.push({
      from: array[i],
      to: array[i+1]
    })
  }

 return result
}
Gyumeijie
  • 174
  • 7