This is what I came up with:
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
function sumTotal() {
for(var i = 0; i < nestedArr.length; i++) {
for(var j = 0; j < nestedArr[i].length; j++) {
for(var k = 0; k < nestedArr[i][j].length; k++) {
var arrNumSum = nestedArr[i][j][k];
arrNumSum += arrNumSum;
return arrNumSum;
}
}
}
}
sumTotal();
You can instead create recursive function using reduce()
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
function sum(arr) {
return arr.reduce(function(r, e) {
return r + (Array.isArray(e) ? sum(e) : e)
}, 0)
}
console.log(sum(nestedArr))
You're overwriting arrNumSum each time through the loop. Moreover, you're returning too soon, right after the first iteration. Try this instead:
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
function sumTotal() {
var arrNumSum = 0;
for(var i = 0; i < nestedArr.length; i++) {
for(var j = 0; j < nestedArr[i].length; j++) {
for(var k = 0; k < nestedArr[i][j].length; k++) {
arrNumSum += nestedArr[i][j][k];
}
}
}
return arrNumSum;
}
console.log(sumTotal());
You could use a recusive call of Array#reduce with a named function as callback.
var array = [[[1, 2], [3, 4]], [[5, 6]]],
total = array.reduce(function add(r, a) {
return Array.isArray(a) ? a.reduce(add, r) : r + a;
}, 0);
console.log(total);
Related
function birthdayCakeCandles(n, ar) {
// Complete this function
ar.sort();
var biggestNo = ar[(ar.length - 1)];
var total = 0;
for (var i = 0; i < ar.length; i++) {
if (ar[i] === biggestNo)
total++;
}
return total;
}
Here's the problem - https://www.hackerrank.com/challenges/birthday-cake-candles/problem
There is no need to sort the array, you can do the problem in O(n) times
function birthdayCakeCandles(arr, n) {
var total = 0;
var len = arr.length;
for (var i = 0; i < len; i++) {
if (ar[i] === n)
total++;
}
return total;
var array = [[2,3,4],[4,5,6],[2,3,9],[7,8,1]];
var number = 3;
If I have this nested array and this variable how do I return the index of the sub-arrays where the number is present. So the final result should be 1 and 3.
Try:
array.reduce((acc, subArr, i) => {
if (!subArr.includes(number)) {
acc.push(i);
}
return acc;
}, [])
The solution using Array.prototype.forEach() and Array.prototype.indexOf() functions:
var arr = [[2,3,4],[4,5,6],[2,3,9],[7,8,1]],
number = 3,
result = [];
arr.forEach(function(v,i){
if (v.indexOf(number) === -1) result.push(i);
});
console.log(result);
function X(a){
var r = [];
for(var i = o ; i < a.length; i++)
for(var j = o ; j < a[i].length; i++)
if(a[i][j] === number)
r.push(i);
return r;
}
i think this should do it. i have just written it here so might have some syntax errors
Since the question is super inconsistent, if you want the index of the subarrays that do have the number, do this:
var foundIndices = [];
for(var y = 0;y < array.length; y++) {
for(var x = 0;x < array[y].length; x++) {
if(array[y][x] == number) {
foundIndices[foundIndices.length] = y;
}
}
}
Otherwise, do this:
var foundIndices = [];
var found = false;
for(var y = 0;y < array.length; y++) {
found = false;
for(var x = 0;x < array[y].length; x++) {
if(array[y][x] == number) {
found = true;
}
}
if(found == false) {
foundIndices[foundIndices.length] = y;
}
}
I have the following array as an example;
let arr = [['red','blue','pink],['dog','cat','bird'],['loud', 'quiet']]
I need to write a generalized function that prints all combinations of one word from the first vector, one word from the second vector, etc. I looked up some codes on here but they are all recursion or working only with the specific array. How can I write this code without recursion?
let allComb = function(arr) {
if (arr.length == 1) {
return arr[0];
} else {
let result = [];
let arrComb = allComb(arr.slice(1));
for (let i = 0; i < arrComb.length; i++) {
for (let j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + ' ' + arrComb[i]);
}
}
return result;
}
}
allComb(arr)
This version uses a single increment per cycle technique with no recursion.
let arr = [
['red', 'blue', 'pink'],
['dog', 'cat', 'bird'],
['loud', 'quiet']
];
function allComb(arr) {
var total = 1;
var current = [];
var result = [];
for (var j = 0; j < arr.length; j++) {
total *= arr[j].length;
current[j] = 0;
}
for (var i = 0; i < total; i++) {
var inc = 1;
result[i] = "";
for (var j = 0; j < arr.length; j++) {
result[i] += arr[j][current[j]] + ' ';
if ((current[j] += inc) == arr[j].length)
current[j] = 0;
else
inc = 0;
}
}
return (result);
}
console.log(allComb(arr));
You may do as follows;
var arr = [['red','blue','pink'],['dog','cat','bird'],['loud', 'quiet']],
res = arr.reduce((p,c) => p.reduce((r,x) => r.concat(c.map(y => x + " " + y)),[]));
console.log(res);
Hi I am developing one jquery application. I am trying to compare the two arrays. For example,
Firstarray=["Mike","Jack"];
SecondArray=["Mike","Jack","Andy","Cruz"];
Whenever we compare above two arrays I want to return the strings which exists in both arrays or which are common to both arrays!
I tried as below. This piece of code is not working.
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
alert('found ' + SecondArray[j]);
return;
}
}
}
Can anyone help me in this regards! Thank you very much.
You can use indexOf() function
Firstarray=["Mike","Jack"];
SecondArray=["Mike","Jack","Andy","Cruz"];
var result = new Array();
for (var i = 0; i < Firstarray.length; i++) {
if(SecondArray.indexOf(Firstarray[i])>=0){
result.push(Firstarray[i]);
}
}
console.log(result);
Here is a solution using Array.prototype.filter and Array.prototype.some along with some ES6 flavor thrown in - see demo below:
var firstArray=["Mike","Jack"];
var secondArray=["Mike","Jack","Andy","Cruz"];
var result = secondArray.filter(a => firstArray.some(b => a === b));
console.log(result);
check this How can I find matching values in two arrays?
Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};
var FirstArray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var commonArray = Array();
var count=0;
for (var i=0; i<FirstArray.length; i++) {
for (var j=0;j< SecondArray.length;j++) {
if (FirstArray[i] == SecondArray[j]){
commonArray[count]=FirstArray[i];
count++;
}
}
}
console.log(commonArray);
Try changing few things in your code :
var Firstarray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var matchedData = [];
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
matchedData.push(SecondArray[j]);
}
}
}
alert(matchedData);
working fiddle :
https://jsfiddle.net/o3brcsvw/
try this
var Firstarray=["Mike","Jack"];
var SecondArray=["Mike","Jack","Andy","Cruz"];
var matchedData = [];
for (var i = 0; i < Firstarray.length; i++) {
for (var j = 0; j < SecondArray.length; j++) {
if (Firstarray[i] == SecondArray[j]) {
//alert('found ' + SecondArray[j]);
matchedData.push(SecondArray[j]);
}
}
}
return matchedData;
I am looking to create a function in javascript, which would allow me to pass a long array, together with one argument.
what I'm looking for is something like this:
var ar = [1,2,3,4];
var pairs = superAwesomeFunction(ar,2) //=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]];
var trebles = superAwesomeFunction(ar,3) //=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]
ideally, the function would have no limit on the folding argument.
I wrote a piece of code that looks like this, which is working fine, but it's not really useful as it isn't universal, and I would need a lot of such functions, which seems silly.
getAll2Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
combinations.push([ar[i], ar[j]]);
}
}
return combinations;
},
getAll3Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
for (var k = j + 1; k < numOdds; k++) {
combinations.push([ar[i], ar[j], ar[k]]);
}
}
}
return combinations;
};
},
... (not so great :|)
getAll8Folds: function (ar) {
var combinations = [],
numOdds = ar.length;
for (var i = 0; i < numOdds; i++) {
for (var j = i + 1; j < numOdds; j++) {
for (var k = j + 1; k < numOdds; k++) {
for (var l = k + 1; l < numOdds; l++) {
for (var m = l + 1; m < numOdds; m++) {
for (var n = m + 1; n < numOdds; n++) {
for (var o = n + 1; o < numOdds; o++) {
for (var p = o + 1; p < numOdds; p++) {
combinations.push([ar[i], ar[j], ar[k], ar[l], ar[m], ar[n], ar[o], ar[p]]);
}
}
}
}
}
}
}
}
return combinations;
}
I'm free to use underscore, jquery or whatever tool i want, but can't find an elegant solution, which would also be performant. ideas?
Thanks
Basically combine() takes an array with the values to combine and a size of the wanted combination results sets.
The inner function c() takes an array of previously made combinations and a start value as index of the original array for combination. The return is an array with all made combinations.
The first call is allways c([], 0), because of an empty result array and a start index of 0.
var arr = [1, 2, 3, 4, 5, 6, 7];
function combine(a, size) {
function c(part, start) {
var result = [], i, l, p;
for (i = start, l = arr.length; i < l; i++) {
// get a copy of part
p = part.slice(0);
// add the iterated element to p
p.push(a[i]);
// test if recursion can go on
if (p.length < size) {
// true: call c again and concat it to the result
result = result.concat(c(p, i + 1));
} else {
// false: push p to the result, stop recursion
result.push(p);
}
}
return result;
}
return c([], 0);
}
out(JSON.stringify(combine(arr, 2), null, 4), true);
out(JSON.stringify(combine(arr, 3), null, 4), true);
out(JSON.stringify(combine(arr, 4), null, 4), true);
out(JSON.stringify(combine(arr, 5), null, 4), true);
out(JSON.stringify(combine(arr, 6), null, 4), true);
// just for displaying the result
function out(s, pre) {
var descriptionNode = document.createElement('div');
descriptionNode.className = 'description';
if (pre) {
var preNode = document.createElement('pre');
preNode.innerHTML = s + '<br>';
descriptionNode.appendChild(preNode);
} else {
descriptionNode.innerHTML = s + '<br>';
}
document.getElementById('out').appendChild(descriptionNode);
}
<div id="out"></div>