phkavitha
phkavitha

Reputation: 847

Need to fetch the numbers from an array

I have got an array of the form:

['32 68', '56 78', '77 99']

I want to o/p another array which will contain the sum of each element in the index using JavaScript (NodeJS). Something like,

['100', '134', '176']

I tried to use .split("") but the double integer number again gets separated as separate digits. Is there any other way to solve this? Please not that, the i/p can be single digit number or double digit.

Upvotes: 2

Views: 477

Answers (3)

user2953222
user2953222

Reputation:

You don't actually need map or anything. For each string we can .split, Numberify, and add.

secondArray[value] = 
    Number((firstArray[value].split(" "))[0]) + 
    Number((firstArray[value].split(" "))[1]);

Modifying this and turning this into a for loop, we get:

var arr2 = [];
for(var i = 0; i < arr.length; i ++){
    arr2.push(
        Number((arr[i].split(" "))[0]) + 
        Number((arr[i].split(" "))[1]));
}
arr = arr2;

Upvotes: 0

JasCav
JasCav

Reputation: 34652

You'll want to get each item, split on a space (if exists) then add up the corresponding split. Something like this:

var origValues = ['32 68', '56 78', '77 99', '7'];
var addedValues = origValues.map(function(value) {
  return value.split(' ')
    .map(function(sArray) {
      return parseInt(sArray);
    })
    .reduce(function(a, b) {
      return a + b;
    });
});

document.write(JSON.stringify(addedValues));

Note that this above example handles the case where you have a single digit inside your array value as well.

To provide some explanation as to what is happening...

  1. You start off taking your original array and you are mapping a function on to each value which is what is passed into that function.
  2. Inside that function, I am splitting the value by a space which will give me an array of (possibly) two values.
  3. I then apply the map function again onto the array and parse each value in the array to an integer.
  4. Last, I reduce the integer array with a summation function. Reduce applies an accumulator function to each item in the array from left to right so you will add up all your values. This result is returned all the way back up so you get your new array with your answers.

Kind of what it looks like in "drawing" form:

Start: origValues = ['32 68', '56 78', '77 99', '7']
Apply map (this will track one value): value = '32 68'
Apply the split: ['32', '68']
Map the parse integer function (I'm going to track both values): [32, 68]
Reduce: 32 + 68 = 100

Upvotes: 5

KJ Price
KJ Price

Reputation: 5984

I don't have time for an explanation (sorry) but, split + reduce will do it.

var arr = ['32 68', '56 78', '77 99'];

var sumArray = arr.map(function (s) {
	return s.split(' ').reduce(function (a, b) {
	  return parseInt(a, 10) + parseInt(b);
	});
});

document.write(JSON.stringify(sumArray));

Upvotes: 4

Related Questions