Home > Net >  Javascript: How to find sum of array for index range and push values into a new array?
Javascript: How to find sum of array for index range and push values into a new array?

Time:09-14

start = [0, 1, 0]   //starting index
end = [1, 5, 5]  //ending index
main = [1, 2, 3, 4, 5, 6]

How would one find the sum of an array, for the given index range, and push sum values into a new array?

Expected output:

[3, 20, 21]

CodePudding user response:

Your question was super unclear... but i guess this is what you are looking for:

var start = [0, 1, 0]   //starting index
var end = [1, 5, 5]  //ending index
var main = [1, 2, 3, 4, 5, 6]

var result = []

for (var i = 0; i < start.length; i  ) {
  let x = start[i]
  let y = end[i]
  result[i] = 0
  for (;x <= y;) result[i]  = main[x  ]
}

console.log(result)

the code would be better to understand if instead of using two separate array you had eg:

lookFor = [{
  start: 0,
  end: 1
}, { 
  start: 1,
  end: 5
}, { 
  start: 0,
  end: 5
}]

something else could be a 2D array of (start & end)

sumUp = [
  [0, 1],
  [1, 5],
  [0, 5]
]

// then you could at least write it as:
result = sumUp.map(([start end]) => {
  return main.slice(start, end).reduce(sumFn, 0)
})

or something like that...

but if you insist on having 2 different array you could also do:

var start = [0, 1, 0]   //starting index
var end = [1, 5, 5]  //ending index
var main = [1, 2, 3, 4, 5, 6]

// then you could at least write it as:
var result = start.map((start, i) => 
  main.slice(start, end[i]   1).reduce((a, b) => a   b)
)

console.log(result)

CodePudding user response:

You can use Array#map and Array#reduce methods as follows:

const 
start = [0, 1, 0],   //starting index
end = [1, 5, 5],  //ending index
main = [1, 2, 3, 4, 5, 6],

output = start.map(
    (s,i) => main.slice(s,end[i] 1).reduce(
        (sum,cur) => sum   cur, 0
    )
);

console.log( output );

  • Related