Samurai Jack
Samurai Jack

Reputation: 3135

Map the elements of bi-dimensional array ignoring the last sub-array

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?

Upvotes: 0

Views: 59

Answers (2)

Ele
Ele

Reputation: 33726

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);

Upvotes: 1

messerbill
messerbill

Reputation: 5639

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)

Upvotes: 0

Related Questions