How do I sum up 2 dimensional array, ex index 0+index0 - javascript

I encountered a problem!
for example! here is my 2 dimensional array: var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
and my desired outcome is : [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
the [6,9,12,15] came from adding the same index numbers of the previous inner arrays. (ex 1+2+3, 2+3+4, 3+4+5, 4+5+6 more clear : index 1 + index 1+ index1 produces 9)
I am so confused so far, the closes i did was to sum up [1,2,3,4][2,3,4,5][3,4,5,6], but I cant seem to do something with each and individual numbers :(
The question requested me to do nested for loops, So i cant use any thing like reduce, map, flatten, etc...

try with this way:https://jsfiddle.net/0L0h7cat/
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array4 = [];
for (j = 0; j < array[0].length; j++) {
var num =0;
for(i=0;i< array.length;i++){
num += array[i][j];
}
array4.push(num);
}
array.push(array4);
alert(array);

Just iterate over the outer array and the inner arrays and add the values to the result array array[3].
var array = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]];
array.forEach(function (a) {
a.forEach(function (b, i) {
array[3] = array[3] || [];
array[3][i] = (array[3][i] || 0) + b;
});
});
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

https://jsfiddle.net/0L0h7cat/
var array = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
];
var sumArr = [];
for (var i = 0; i < array[0].length; i++) {
sumArr[i] = 0;
for (var j = 0; j < array.length; j++)
sumArr[i] += array[j][i];
}
array.push(sumArr);

If you are interested in Arrow Functions, this will work:-
var array = [[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]];
var count = [];
array.forEach(x => x.forEach((y, i) => count[i] = (count[i] || 0) + y));
array.push(count);
console.log(array);
NOTE: Not cross browser support yet.

This is how -
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array2=[]
for (var i = array[0].length;i--;) {
var sum=0;
for (var j = array.length; j--;) {
sum=sum+array[j][i];
}
array2.push(sum)
}
array.push(array2.reverse());
document.write('<pre>'+JSON.stringify(array) + '</pre>');
But I'm sure there are more elegant methods. I'm just learning by answering questions myself.

A simplistic approach with just conventional for loops
var input = [[1,2,3,4],[2,3,4,5],[3,4,5,6]];
function getSumOfArrayOfArrays(inputArray) {
var length = inputArray.length;
var result = [];
for(var i=0; i<length; i++){
for(var j=0; j<=3; j++){
result[j] = result[j] ? result[j] + inputArray[i][j] : inputArray[i][j];
}
}
return result;
}
var output = getSumOfArrayOfArrays(input); // [6,9,12,15]
var desiredOutput = input;
desiredOutput.push(output)
document.write(JSON.stringify(desiredOutput));
// [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]

I try to avoid writing nested for loops.
var arrayOfArrays=[
[1,2,3,4],
[2,3,4,5],
[3,4,5,6]
];
//define a function to extend the Array prototype
Array.prototype.add = function(otherArray){
var result = [];
for(var i = 0; i < this.length; i++) {
result.push( this[i] + otherArray[i] )
}
return result;
};
//reduce array of arrays to get the result array `sum`
var sum = arrayOfArrays.reduce(function(arrayA, arrayB){
//`arrayA`+`arrayB` becomes another `arrayA`
return arrayA.add(arrayB)
});
//put `sum` back to `arrayOfArrays`
arrayOfArrays.push(sum);
document.write('<pre>' + JSON.stringify(arrayOfArrays) + '</pre>');

Related

I am just wondering what is going wrong with my code of adding 2 arrays in javascript

I did try this
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 3, 4, 5, 6];
var sum = [];
for (var i = 0; arr1[i] < arr1.length; i++) {
for (var j = 0; arr2[j] < arr2.length; j++) {
sum = sum.push(arr1[i] + arr2[j]);
}
}
console.log(sum);
Found the right solution, However trying to understand where my code is going wrong. It says sum is not defined.
Do let me know or any ref would also do good.
Thanks Folks
Array.push does not return a new array. It modifies the given array. So basically you just need to change:
sum = sum.push(arr1[i] + arr2[j]);
To:
sum.push(arr1[i] + arr2[j]); //without the assignment
And it should work!
Assuning you want a new array with sum of each value at same index, you could take a single loop and add the values at same index.
Array#push returns the new length of the array, and has nothing to do with the pushed value.
var arr1 = [1, 2, 3, 4, 5],
arr2 = [2, 3, 4, 5, 6],
sum = [];
for (var i = 0; i < arr1.length; i++) {
sum.push(arr1[i] + arr2[i]);
}
console.log(sum);
Array.push is mutating the original array. And it will return length of updated array. so while call on 2 nd time the sum is number not array .Thats why you got error
so should not reassign sum = sum.push
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [2, 3, 4, 5, 6];
var sum = [];
for (var i = 0; arr1[i] < arr1.length; i++) {
for (var j = 0; arr2[j] < arr2.length; j++) {
sum.push(arr1[i] + arr2[j]);
}
}
console.log(sum);

Group items in for loops

Using JavaScript, I am looping through an array of values.
var values = [1, 2, 1, 3, 1, 3, 4, 1]
for (let i = 0; i < values.length; i++) {
console.log(values[i])
}
I want to get the sum for each group of 4. I could do this in multiple for loops by using:
var values = [1, 2, 1, 3]
var sum1 = 0
for (let i = 0; i < values.length; i++) {
sum1 += parseInt(values[i]);
}
var values = [1, 3, 4, 1]
var sum2 = 0
for (let i = 0; i < values.length; i++) {
sum2 += parseInt(values[i]);
}
How can I group by 4 and get the sum of the values for each group by using one for loop?
Can slice() the array and reduce() each sub array
var values = [1, 2, 1, 3, 1, 3, 4, 1]
var sums =[];
for(let i=0; i< values.length; i=i+4){
const subArr= values.slice(i,i+4);
const sum = subArr.reduce((a,c)=>a+c)
sums.push(sum)
}
console.log(sums)
You can use a counter. Reset the counter and sum variable when it reaches the group limit, like below example :
var values = [1, 2, 1, 3, 1, 3, 4, 1];
var result = [];
var counter = 0;
var sum = 0;
for(var i = 0; i < values.length; i++){
counter++;
sum += values[i];
if(counter === 4 || i === values.length-1){
result.push(sum);
counter = 0;
sum = 0;
}
}
console.log(result);
You could take an array as result set and divide the index by 4 and take the integer value for adding the value.
var values = [1, 2, 1, 3, 1, 3, 4, 1],
grouped = values.reduce((r, v, i) => {
var k = Math.floor(i / 4);
r[k] = r[k] || 0;
r[k] += v;
return r;
}, []);
console.log(grouped);

What is the difference between [4,null,6] and [4,6]

Here is the question:
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
And here is my code:
function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
delete arr2[j];
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
Please, tell me my mistakes.
If you work using indices as references which you delete, you'll leave those indices undefined.
You have to use push to add an item and splice to remove one.
The time complexity of the following code should be: O(nm) where n and m are the lengths of the arr1 and arr2 arrays respectively.
function diffArray(arr1, arr2) {
var newArr = [];
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
arr2.splice(j, 1);
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
This should work, but I've found a different way that is a bit slower for short arrays but much faster for longer array.
The time complexity of the following code should be: O(3(n + m)), which is reduced to O(n + m) where n and m are the lengths of the arr1 and arr2 arrays respectively.
Look at this fiddle.
Here's it:
function diffArray(arr1, arr2) {
let obj1 = {}, obj2 = {};
for (let l = arr1.length, i = 0; i < l; i++)
obj1[arr1[i]] = undefined;
for (let l = arr2.length, i = 0; i < l; i++)
obj2[arr2[i]] = undefined;
let a = [];
for (let arr = arr1.concat(arr2), l = arr.length, i = 0, item = arr[0]; i < l; i++, item = arr[i])
if (item in obj1 !== item in obj2)
a.push(item);
return a;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
The task you are trying to complete asks you to create a new array, but instead you modify arr2. It would probably be easiest to just copy all elements not included in the other array to a new array, like this:
function diffArray(arr1, arr2) {
var newArray = [];
arr1.forEach(function(el) {
if (!arr2.includes(el)) {
newArray.push(el);
}
});
arr2.forEach(function(el) {
if (!arr1.includes(el)) {
newArray.push(el);
}
});
return newArray;
}
If you would rather try and fix your code instead, I can try to have another look at it.
I've used Array.prototype.filter method:
function diffArray(arr1, arr2) {
var dif01 = arr1.filter(function (t) {
return arr2.indexOf(t) === -1;
});
var dif02 = arr2.filter(function (t) {
return arr1.indexOf(t) === -1;
});
return (dif01).concat(dif02);
}
alert(diffArray([1, 2, 3, 6, 5], [1, 2, 3, 4, 7, 5]));
If you still want to use your code and delete the common elements, try to use Array.prototype.splice method instead of delete: the latter deletes the value, but keeps the index empty, while Array.prototype.splice will remove those whole indices within the given range and will reindex the items next to the range.
You can use Array.prototype.filter:
var array1 = [1, 2, 3, 5];
var array2 = [1, 2, 3, 4, 5];
var filteredArray = filter(array1, array2).concat(filter(array2, array1));
function filter(arr1, arr2) {
return arr1.filter(function(el) { return arr2.indexOf(el) < 0; });
}
Here is a working JSFiddle.
Try this:
function diffArray(arr1, arr2) {
var ret = [];
function checkElem(arrFrom, arrIn) {
for (var i = 0; i < arrFrom.length; ++i) {
var elem = arrFrom[i];
if (arrIn.indexOf(elem) === -1)
ret.push(elem);
}
}
checkElem(arr1, arr2);
checkElem(arr2, arr1);
return ret;
}
I hope this can solve your problem.

reverseArrayInPlace eloquentJS

I figured out a simple way to solve this, and it worked out.
var reverseArrayInPlace = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result.unshift(arr[i]);
}
for(var j = 0; j < result.length; j ++) {
arr[j] = result[j];
}
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//[5,4,3,2,1]
However, i'm wonder why can't I use an even simpler way by just assign the arr argument to the result value which is [5,4,3,2,1]? But the code below doesn't work, it still prints out [1,2,3,4,5].
var reverseArrayInPlace = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result.unshift(arr[i]);
}
arr = result;
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//[1,2,3,4,5]
Try this in your dev console:
var arr = [1,2,3];
function retArr(arr){
var res = arr;
res = [3,2,1];
return res;
}
retArr(arr); // returns 3,2,1
console.log(arr); // logs 1,2,3
All you did was create a new array!
Parameters of functions are pass-by-value.
the reason direct for-loop access works is because array properties are pass-by-reference.
P.S. an actual in-place reversal would look like this:
function reverseInPlace(array){
var swap = function(i,j){
var t = array[i];
array[i] = array[j];
array[j] = t;
};
for (var i = 0; i < array.length/2;i++){
swap(i,array.length-i-1);
}
}
Try using .slice(), .pop()
var reverseArrayInPlace = function(arr) {
var copy = arr.slice(0);
for (var n = 0; n < arr.length; n++) {
arr[n] = copy.pop();
}
return arr
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
Alternatively, using Array.prototype.sort()
var reverseArrayInPlace = function(arr) {
arr.sort(function(a, b, index) {
return index < index + 1 ? -1 : 1
});
};
//test
var arrayValue = ["a", "b", "c", "d", "e"];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

How to get common value from 4 different array with javascript

I have below arrow and I want to get common value from all four array. I have try below code and it's working but not the correct way I want. Instead of coming [2, 3] in new array it showing other value which are common at least in two or three array.
Fiddle Demo
My Code
var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5, 3],
result = [],
common = [];
function findCommon () {
for(var i = 0; i < arguments.length; i++){
var garr = arguments[i];
result = result.concat(arguments[i]);
};
}
findCommon(a,b,c,d);
var sorted_arr = result.sort();
for(var i = 0; i< result.length-1; i++){
if(result[i+1] == sorted_arr[i]){
common.push(result[i]);
}
};
alert(common); //[2, 2, 2, 3, 3, 4, 5]
You could use arrays as the values of an object, and use the numbers as the keys. It makes it easy to count the numbers then. Note, this code is also future proof, so that if you want fewer or more arrays to test, this will let you. It also de-dupes the individual arrays, so numbers within each are only counted once to prevent errors.
function findCommon() {
var obj = {};
var out = [];
var result = [];
// convert arguments to a proper array
var args = [].slice.call(arguments);
var len = args.length;
for (var i = 0, l = len; i < l; i++) {
// grab a de-duped array and and concatenate it
// http://stackoverflow.com/a/9229821/1377002
var unique = args[i].filter(function(item, pos) {
return args[i].indexOf(item) == pos;
});
result = result.concat(unique);
}
for (var i = 0, l = result.length; i < l; i++) {
var el = result[i];
// if the object key doesn't exist, create an array
// as the value; add the number to the array
if (!obj[el]) obj[el] = [];
obj[el].push(el);
}
for (var p in obj) {
// if the array length equals the original length of
// the number of arrays added to the function
// add it to the output array, as an integer
if (obj[p].length === len) out.push(+p);
}
return out;
}
findCommon(a, b, c, d); // [2]
In addition, this will find all multiple keys, so if you replace the 5 in d as 3, the result will be [2, 3].
DEMO which uses 4 arrays, multiple hits
DEMO which uses 5 arrays
Try this:
function findCommon()
{
var common=[];
for(i=0; i<a.length; i++)
{
if(b.indexOf(i) != -1 && c.indexOf(i) != -1 && d.indexOf(i) != -1)
{
common.push(i);
}
}
return common;
}
This will return array of common values between all four arrays. Here is the working fiddle.
Assuming you want something generic for X arrays and we are talking about integers this sounds to me like some bucket business.
var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5];
function findCommon()
{
var bucket = [];
var maxVal = 0;
var minVal = 0;
for(var i = 0; i < arguments.length; i++)
{
for(var j = 0 ; j < arguments[i].length ; j++)
{
var val = arguments[i][j];
bucket[val] = bucket[val] + 1 || 1;
if(val > maxVal)
{
maxVal = val;
}
else if(val < minVal)
{
minVal = val;
}
}
}
var retVal = 0;
var maxTimes = 0;
for(var i = minVal ; i <= maxVal ; i++)
{
var val = bucket[i];
if(val > maxTimes)
{
maxTimes = val;
retVal = i;
}
}
return retVal;
}
console.log(findCommon(a,b,c,d));
JSFIDDLE.
You cna use indexOf to resolve that:
array.indexOf(element) >=0 // it means that element is in array
or
array.indexOf(element) != -1
When you would be using jQuery, thre is a shorter version:
$.inArray(value, array)
More fancy way, would be to use filter (Filter):
function hasElement(element, index, array) {
return element.indexOf(i) >= 0;
}
filtered = [a,b,c,d].filter(hasElement);
filtered.length === 4
This Try,
will find the common number with number of times it repeated.
var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5],
result = [],
common = [];
var all = a.concat(b).concat(c).concat(d);
var commonNum=0;
var largestCounter=0
for(var i = 0; i< all.length-1; i++){
var counter=0;
if(a.indexOf(all[i])>-1) counter+=1;
if(b.indexOf(all[i])>-1) counter+=1;
if(c.indexOf(all[i])>-1) counter+=1;
if(d.indexOf(all[i])>-1) counter+=1;
if(counter>largestCounter)
{largestCounter = counter;
commonNum = all[i];
}
};
alert(commonNum+" with count " + largestCounter);

Categories

Resources