How to sum elements of two multidimensional arrays? - javascript

I have 2 multidimensional arrays:
[[230.0], [10.0], [12.0]]
[[50.0], [60.0], [89.0]]
And am trying to sum each element together and keep the same array structure. So it should look like:
[[280.0], [70.0], [101.0]]
I tried this:
var sum = array1.map(function (num, index) {
return num + array2[index];
});
But I get this:
[23050, 1060, 1289]
Any help would be appreciated. Thanks.

The code, you use, takes only a single level, without respecting nested arrays. By taking na array with only one element without an index of the inner array and using an operator, like +, the prototype function toString is invoced and a joined string (the single element as string, without , as separator) is returned and added. The result is a string , not the result of a numerical operation with +.
You could take a recursive approach and check if the value is an array, then call the function again with the nested element.
function sum(a, b) {
return a.map((v, i) => Array.isArray(v) ? sum(v, b[i]) : v + b[i]);
}
console.log(sum([[230], [10], [12]], [[50], [60], [89]]))

Make it like this
var sum = array1.map(function (num, index) {
return parseInt(num) + parseInt(array2[index]);
});
You should have to make parseInt or parseFloat so it can convert string with them

STEPS
Iterate through every number in the array (array length).
Sum the objects of the same index in both of the arrays.
Push the sum into another array for the result. Use parseFloat if the input is string.
(Optional) use .toFixed(1) to set decimal place to have 1 digit.
const arr1 = [[230.0], [10.0], [12.0]]
const arr2 = [[50.0], [60.0], [89.0]]
let sum = []
for (let i = 0; i < arr1.length; i++){ // Assume arr1 and arr2 have the same size
let eachSum = parseFloat(arr1[i]) + parseFloat(arr2[i])
sum.push([eachSum.toFixed(1)])
}
console.log(sum)

You are trying to add two arrays structures inside the map function.
so one solution so you can see what is happening is this...
array1.map((a,i) => a[0] + array2[i][0])
screenshot from the console...

Inside map fn you should:
return parseInt(num) + parseInt(array2[index]);
This is happening because when you are trying to add them, these variable are arrays and not integers. So they are evaluated as strings and concatenated.

Related

Javascript array sorting using regex

I want to sort an array of phone numbers and have the length of the array outputted based on areacode. For example:
var nums = [
8881756223,
8881742341,
9187221757,
...,
]
there are a lot more entries than that (roughly 1300) and its already in numerical order. However, what I want it to do is:
1. look at the first 3 numbers of the first entry
2. look at the next entries first 3 numbers
3. if they are different, then splice the array, console.log new array.length
and console.log that area code
so for example, the first two numbers in the array i provided will be spliced into their new array, and the console output will be:
areacode: 888, length: 1
areacode: 918, length: 0
I know the regex to search for the first the numbers, but I don't exactly know how to splice them into their own arrays...Like i know, use splice, but comparing the two with logic statements, I've never had to do something like that before while using a regular expression.
what I have so far is this:
const patt = new RegExp('^\d{3}')
var newArr = nums.filter(x => patt)
for (var i = 0; i < newArr.length; i++)
console.log(newArr[i])
but this is spitting out the full number, not the area code its self. Of course ill be adding the logic to sort after i get it to just spit out area codes.
I suggest using
nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'))
Here,
"" + x will coerce the number to string
.replace(/^(\d{3})[^]*/, '$1') will remove all chars keeping the first 3 digits (or the whole string upon no match).
JS Demo:
var nums = [
8881756223,
8881742341,
9187221757,
1
];
var res = nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'));
console.log(res);
you can try this
var nums = [
8881756223,
8881742341,
9187221757
]
var prefixes = nums.map(x=>(x+"").substr(0,3));
var votes = prefixes.reduce(
(votes, curr) => {
if(votes[curr]) votes[curr]++;
else {votes[curr] =1;}
return votes;
}, {});
var ans = Object.keys(votes).map(x => ({areacode:x, length:votes[x]}));
console.log(ans);
ans will hold the value you require
vote counting technique i used is explained here https://igghub.github.io/2017/01/15/useful-js-reduce-trick/

Using reduce in Javascript to sum both empty and non empty arrays

I am trying to find a way to write a function that sums up all the elements within an array. I have been trying to implement this using JavaScripts reduce function. The problem I am having is that i want this function to work on both an empty array and an array with elements as separate scenarios. The following example passes the test case for an empty array but then not when the array has elements and vice versa.
function sum (numbers) {
numbers = ['a', 'b', 'c'];
return numbers.reduce(function (x, y, i) {
return x + y + i;
}), 0 };
I was looking at the signature of the reduce function and trying to implement this on the basis of that but something seems to be missing in my knowledge here.
function (previousValue, currentElement, currentIndex, array)
the following works with both an array of numbers, and an empty array (where the result will obviously be zero)
var sum = numbers.reduce(function(prev,curr){
return curr + prev;
},0);
Below is a demo of both your scenarios
function sum(numbers){
var x = numbers.reduce(function(prev,curr){
return curr + prev;
},0);
return x;
}
alert(sum([1,2,3]));
alert(sum([]));

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.
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...
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.
Inside that function, I am splitting the value by a space which will give me an array of (possibly) two values.
I then apply the map function again onto the array and parse each value in the array to an integer.
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
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));
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;

Arrays and strings in javascripts

Array1 = ['1,2,3']
How can I retrieve the numerical values by transforming it into non-string?
I've been trying parseInt, but I can only manage to get 1 as end-result.
Thanks.
If you start with an array containing a string, like in your example, you need to use split().
Example:
Array1 = ['1,2,3'];
var new_array = Array1[0].split(','); // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]
I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?
If you can, re-work your design to actually use an array of integers, so use:
var arr = [1,2,3];
instead of ['1,2,3'].
If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:
var array1 = ['1,2,3', '4,5,6,7'];
function as_int_array(list, index) {
return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]
Hope that helps.
Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.
Why you are getting 1 !!!
Whenever you are using parseInt() it tries to read your input character by character. So according to your input
var Array1 = ['1,2,3'];
first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.
Solution of your problem :
var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);

javascript sorting an array of strings

I am having seemingly inconsistent results trying to sort arrays of strings using the sort method, both with and without passing sort() a function:
function sortThese(strArr) {
var words = [];
for (var i = 0; i < strArr.length; i++) {
words.push(String(strArr[i].length + "," + strArr[i]));
}
words = words.sort();
console.log(words);
}
sortThese(["battt","catt","mat"]);
sortThese(["as","assssvvvvt","affggg"]);
in this case my results are:
["3,mat", "4,catt", "5,battt"]
["10,assssvvvvt", "2,as", "6,affggg"]
so it appears that the method is seeing my "10" as "1."
How do I make it see the value as 10?
Futher, if I pass sort this function:
words = words.sort(function(a,b){
return a - b;
});
the result is not sorted:
["4,catt", "5,battt", "3,mat"]
["2,as", "10,assssvvvvt", "6,affggg"]
I would love some clarification regarding how I should expect the sort method to behave, and how to make it sort these strings! Thank you
The "10" comes before "3", because you've made it into a string (ie, "1" comes before "3"). If you want to sort by length, you could use the sort function to compare lengths:
words.sort(function(a, b) { return a.length > b.length; });
Fiddle
You could also create a nested object array, in order to hold a number and the string in each item:
var words = strArr.map(function(str) {
return { len: str.length, str: str }
});
words.sort(function(a, b) { return a.len > b.len; });
(Of course, this second approach is unnecessary for the example case, but may be useful in other cases.)
Fiddle
Sorting strings always uses alphabetical order, not numerical. Just imagine 0=A 1=B 2=C and so on. Letters are not connected as numbers, so everything starting with 1 (respective B) will be sorted before 2 (respective C). That's why you get 10,2,6. For 10, only the 1 counts.
Using a custom sort function is a good way to achieve this. But you cannot subtract strings. Extract the integer before and compare afterwards:
words = words.sort(function(a,b){
//parseInt will read only the first numbers and discard the letters after this
return parseInt(a) - parseInt(b)
});

Categories