0

Let say that there is this matrix:

myArray = [["a", 6, 5.54, "b"],
           ["xxx", 65.5, 45],
           [343, "abc", 0.09]];

My goal is to compute the sum of each sub-array but ignoring the last sub-array, it this case [343, "abc", 0.09]. Also, ignoring the string values.

I managed to do it for all the sub-arrays and it looks like this:

myArray = [["a", 6, 5.54, "b"],
           ["xxx", 65.5, 45],
           [343, "abc", 0.09]];

result = myArray.map(a => a.reduce((s, v) => s + (+v || 0), 0));
console.log(result)

Don't know which condition to add in order to ignore the last sub-array.

Any ideas?

3
  • It doesn't really make sense to do that with .map(), because it's intended to be used to produce a value for every element of the source array. You could use .reduce() instead, and just not change the accumulator in the last call to the callback. Commented Feb 26, 2018 at 15:36
  • The reduce function also takes two additional arguments: the index and the array. That should get you what you need to determine whether you're on the last index. Commented Feb 26, 2018 at 15:39
  • That's easily done with a simple loop. Commented Feb 26, 2018 at 15:39

2 Answers 2

1

Use the function slice(0, -1).

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

Second param: A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.

var myArray = [
  ["a", 6, 5.54, "b"],
  ["xxx", 65.5, 45],
  [343, "abc", 0.09]
];

var result = myArray.slice(0, -1).map(a => a.reduce((s, v) => s + (+v || 0), 0));

console.log(result);

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

Comments

0

i'd do it that way (if it is always the last element, remove it using pop()):

myArray = [["a", 6, 5.54, "b"],
           ["xxx", 65.5, 45],
           [343, "abc", 0.09]];
           
myArray.pop()

result = myArray.map(a => a.reduce((s, v) => s + (+v || 0), 0));
 
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.