0

I have an array of numbers, that I want to map into a new array of numbers.

let numbers= [1,3,5,10,11]

needs to be turned into

var result = [4,8,15,21,11];

i tried using ES6 shorthand syntax, to do it. But there is not really any coherence between the numbers, so i though a callback would be better

let numbers= [1,3,5,10,11]

const result = numbers.map(x => resultBinding(x))


function resultBinding(x){

}

now my issue here is that I don't want to try to avoid making a lot of if-statements to determinate each value.

2
  • 1
    what is the logic of 1 getting converted to 4 and so on? Commented Dec 22, 2018 at 14:11
  • 1
    This was an assignment, given y my teachers, there is no real logic behind it. I also think this is a strange task, since this has little relevance to an actual project.. Commented Dec 22, 2018 at 14:12

3 Answers 3

4

I'd use reduce to keep track of the previous array value using the accumulator:

 const result = [];
 array.reduce((a, b) => (result.push(a + b), b));
 result.push(array.pop()); // add the trailing 11
Sign up to request clarification or add additional context in comments.

Comments

3

Iterate it with Array.map(). Combine the current item, and the next item (or 0 if undefined):

const numbers= [1,3,5,10,11]

const result = numbers.map((n, i) => n + (numbers[i + 1] || 0));
  
console.log(result);

Comments

3

operation of result = [1+3, 3+5, 5+10, 10+11, 11]. last index of result is same as numbers array because there is no index after that.

let numbers= [1,3,5,10,11];

let result = numbers.map((num, index)=> (index+1) >= numbers.length ? num : num + numbers[index+1])

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.