1

I'm trying to write a function that continually adds together the first and last elements of an array using forEach with array.shift() + array.pop().

The problem is that the for-loop doesn't complete the innermost numbers, and so the array is always left with 2 values inside of it.

Code:

function choreAssignment(chores) {
  chores.sort(function(a, b) {return a - b});
  var assignment = [];
  chores.forEach(function() {
  assignment.push((chores.pop() + chores.shift()));
});
  return assignment.sort(function(a, b) {return a - b});
}

The above code works as expected, but it leaves the innermost two values inside the chores array.

For example if I run:

Code:

var arr = [1, 4, 7, 2, 5, 9, 4, 3];
choreAssignment(arr);

I get:

[8, 9, 10]

Ie, it adds 9 & 1, 7 & 2, 5 & 3, but it leaves [4, 4] inside the array.

I'm not sure why this is. Thank you.

2
  • 1
    Your example and description do not seem to match up. I would expect the output to be [4, 8, 16, 7] for the sample input [1, 4, 7, 2, 5, 9, 4, 3]. Commented Dec 26, 2016 at 19:45
  • It first sorts the chores algorithm from smallest value to largest. So before it uses >shift() and pop() the values are listed as[1, 2, 3, 4, 4, 5, 7, 9] so it adds together 9+1, 7+2, and 5+3, but not 4+4 for some reason. Commented Dec 26, 2016 at 19:50

1 Answer 1

3

Try changing the forEach to:

while (chores.length) {
    assignment.push((chores.pop() + chores.shift()));
}

Note this assumes there are always an even number of elements in array

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, this worked. Could you elaborate on why this method worked but forEach didn't? I don't see why one would work and not the other.
@JonathanBechtel It's usually a bad idea to remove elements from an array while you are iterating over it.
@pzp thank you for the feedback. I was thinking of using reduce but wasn't connecting the dots for it so I went with this method instead. This isn't going to be used in production, it's just kicking the tires.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.