Group items in for loops - javascript

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

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

How to get the position of element index of an array in an ascending order?

let a=[4, 3, 2, 2, 0, 1]
let b=[0, 1, 2, 2, 3, 4]; //My code demo below help to sort a into ascending order.
Output=[4, 5, 2, 3, 1, 0];
// Get the position of element index in a ascending order. For example, 0 is in index 4, 1 is in index 5, 2 is in index 2,2 is in index 3, and 4 is in index 0. Please Provide a demo. Thank you
var Arr = [4, 3, 2, 2, 0, 1];
for (var i = 1; i < Arr.length; i++) {
for (var j = 0; j < i; j++) {
if (Arr[i] < Arr[j]) {
var x = Arr[i];
Arr[i] = Arr[j];
Arr[j] = x;
}
}
}
console.log(Arr);
You could get the indices of the unsorted array and sort the indices by the values of the array.
const
array = [4, 3, 2, 2, 0, 1],
indices = [...array.keys()];
indices.sort((a, b) => array[a] - array[b]);
console.log(...indices);
you can use Object.entries :
let a=[4, 3, 2, 2, 0, 1]
let result = Object.entries(a).sort((a,b) => a[1]-b[1]).map(e => +e[0])
console.log(result)
i guess this is what you want
and also i change some other thing in code to be cleaner and readable
you can ask me anything if you want
function sortWithIndex (self) {
let Arr = [4, 3, 2, 2, 0, 1];
let result = [];
let ArrLength = Arr.length;
for (let i = 0; i < ArrLength; i++) {
number = Arr[i];
indexOfNumber = i;
result.push ('index ' + indexOfNumber + ' is ' + number);
};
return result
};
console.log(sortWithIndex());
Mostafa.T 🐍

How to get all substrings (contiguous subsequences) of my JavaScript array?

My task is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].
I am using this code:
let arr = [1, 2, 3, 4];
for (let i = 1; i <= arr.length; i++) {
let a = [];
for (let j = 0; j < arr.length; j++) {
a.push(arr[j]);
if (a.length === i) {
break;
}
}
console.log(a);
}
And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined
What am I missing/doing wrong?
For the inner array, you could just start with the index of the outer array.
var array = [1, 2, 3, 4],
i, j, l = array.length,
result = [];
for (i = 0; i < l; i++) {
for (j = i; j < l; j++) {
result.push(array.slice(i, j + 1));
}
}
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You have two issues in your code:
You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i
You need to remove that break on the length which you have in inner loop.
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
Try this
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
If you don't want to mutate your array.
let arr = [1, 2, 3, 4];
let res = [];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a = [...a, arr[j]];
res = [...res, a];
}
}
console.log(res);
i have prepare stackblitz for this case.
let source = [1,2,3,4];
const output = [];
const arrayMultiplier = (source) => {
const eachValueArray = [];
source.forEach((item, index) => {
// Will push new array who will be sliced source array.
eachValueArray.push(source.slice(0, source.length - index));
});
//We reverse array to have right order.
return eachValueArray.reverse();
};
for(let i = 0; i <= source.length; i++) {
output.push(...arrayMultiplier(source));
source.shift(); // Will recraft source array by removing first index.
}
//Don't forget last item.
output.push(source);
console.log(output);
Is not the most shorten solution but do the job
== update after code review ==
// [...]
const arrayMultiplier = (source) => {
// Will push new array who will be sliced source array.
// We reverse array to have right order.
return source.map((item, index) => source.slice(0, source.length - index)).reverse();
};
// [...]
Use two iteration
get slice array based on loop index.
use sliced array and combine array element.
var arr = [1, 2, 3, 4];
let newArra =[];
arr.map((x,i)=> {
let remainArr = arr.slice(i);
return remainArr.forEach((y, r) => newArra.push(remainArr.slice(0, r+1)))
})
newArra.forEach(x=> console.log(x))

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

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

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