Undefined Array - javascript

i am trying to make a for loop out of a var variable but it doesn't work. For some reason tempArray.length is always undefined, it never return anything different. Can anyone help ?
for (i = 0; i < arr.length; i++) {
tempArray = arr[i];
for (k = 0; k <= tempArray.length; i++) {
if (tempArray[k] != /[0-9]+/) {
countinue;
}

var tempArray = [];
for (i = 0; i < arr.length; i++) {
tempArray = arr[i];
}
for (k = 0; k <= tempArray.length; i++) {
if (tempArray[k] != /[0-9]+/) {
countinue;
}
}
Temp array needs to be set to an array.
Loop through and build tempArray first, then loop through the temp array and do what ever you need to.

Related

'TypeError: Cannot set properties of undefined (setting '0')'----Array assignment

When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.
// r and c are already defined numbers,arr is already defined array.
let n = [[]]
let index = 0
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
n[i][j] = arr[index]
index++;
}
}
return n;
Leetcode told me n[i][j] = arr[index] had error;
Anyone knows why? thanks.
Whenever the value of i becomes 1, inside the inner loop it is setting the value to n[i][j], which is n[1][0], here n[1] is undefined and it is accessing the 0th index value of undefined, that is the reason of the error.
the first iteration works fine because there is already an empty array in the 0th index (when i = 0).
here you can try doing this
let n = []
let index = 0
for (let i = 0; i < r; i++) {
n[i] = [];
for (let j = 0; j < c; j++) {
n[i][j] = arr[index];
index++;
}
}
return n;
As the comments showed, it is possible to use .push.
This is how I implemented that solution in my case.
const myArray = [[]];
const height = 7;
const width = 8;
for (let i= 0; i < height; i++) {
if (i> 0) myArray.push([]); // this initialises the array.
for (let j = 0; j < width; j++) {
myArray[i][j] = "x";
}
}
console.log(myArray)
Here is a codepen

Append element in JSobject

I am trying to create a JS object which has this structure
{ node1:
[ 'test1.1',
'test1.2'],
node2:
['test2.1',
'test2.2']
}
This is my code
for (var k = 0; k < keys.length; i++){
key = keys[k];
var result = {};
var r = [];
for (var i = 0; i < elements.length; i++){
r.push(elements[i]);
}
result[key] = r;
}
the result looks a bit different from my expectation and is not a valid JSON:
{ node1:
[ 'test1.1',
'test1.2'] }
{ node2:
[ 'test2.1',
'test2.2' ] }
I am not sure what is wrong about the code.
Declare var result = {}; outside the for loop and it will work as currently a new object is created inside the loop.
var result = {};
for (var k = 0; k < keys.length; k++) {
key = keys[k];
var r = [];
for (var i = 0; i < elements.length; i++) {
r.push(elements[i]);
}
result[key] = r;
}
You also have i++ in the first loop so change that to k++ otherwise there will be a infinite loop.

possible combinations get a targetTotal counting itself as a case

Trying to count possible combinations to get a targetTotal. Using powerSet returns the sum without adding itself. E.g [1,2,3,5] returns [3+1] for a targetSum of 4, whereas I expect to get [1+1+1+1], [2+2], [3+1].
Do you have any ideas how I could make it count itself first as a case?
function powerset(arr) {
var ps = [[]];
for (var i=0; i < arr.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(arr[i]));
}
}
return ps;
}
function sum(arr) {
var total = 0;
for (var i = 0; i < arr.length; i++)
total += arr[i];
return total
}
function findSums(numbers, targetSum) {
var sumSets = [];
var numberSets = powerset(numbers);
for (var i=0; i < numberSets.length; i++) {
var numberSet = numberSets[i];
if (sum(numberSet) == targetSum)
sumSets.push(numberSet);
}
return sumSets;
}
Example invocation:
findSums([1,2,3,4,5],6); [[2,3], [1,4], [5], [1,1,1,1,1,1], [2,2,2], [3,3]]

Diff an Array (without modifying original arrays)

OBJECTIVE
I am trying to highlight the dfferences between two arrays. Please note that arr1 and arr2 will vary in length and have multiple types present (strings and numbers).
MY CODE
function diff(arr1, arr2) {
var diffArr = [];
if (arr1.length >= arr2.length) {
for (var i = 0; i < arr1.length; i++){
if (arr2.indexOf(arr1[i]) < 0) {
diffArr.push(arr1[i]);
}
}
} else {
for (var j = 0; j < arr2.length; j++){
if (arr1.indexOf(arr2[j]) < 0) {
diffArr.push(arr2[j]);
}
}
}
return diffArr;
}
ISSUES
diff([1, 2, 'cat', 'fish'], [1, 2, 3,'dog']); //returns only ['cat', 'fish']
I am pretty sure that my code is only returning the duplicates in one of the arrays via diffArr.push (even if there are unique values in both arrays). However, I am unsure how to overcome this.
My references
Removes Duplicates from Javascript Arrays
Removed Duplicates from an Array Quickly
Javascript Array Difference
Your code currently only crawls through one array (let's call it A) and pushes in all the A values that don't exist in B. You never go the other way and push in the B values that don't exist in A. There's also no need to have different behavior based on which array is longer. Here is the final answer in a simple way:
function diff(arr1, arr2) {
var diffArr = [];
for (var i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) < 0) diffArr.push(arr1[i]);
}
for (var j = 0; j < arr2.length; j++) {
if (arr1.indexOf(arr2[j]) < 0) diffArr.push(arr2[j]);
}
return diffArr;
}
And in a slightly more functional way:
function diff(arr1, arr2) {
var elsIn1Not2 = arr1.filter(function(el){ return arr2.indexOf(el) < 0; });
var elsIn2Not1 = arr2.filter(function(el){ return arr1.indexOf(el) < 0; });
return elsIn1Not2.concat(elsIn2Not1);
}
Both functions return [ 'cat', 'fish', 3, 'dog' ] for your example.
function diff(arr1, arr2) {
var diffArr = {};
if (arr1.length >= arr2.length) {
for (var i = 0; i < arr1.length; i++){
if (arr2.indexOf(arr1[i]) < 0) {
diffArr[arr1[i]] = 1;
}
}
} else {
for (var j = 0; j < arr2.length; j++){
if (arr1.indexOf(arr2[j]) < 0) {
diffArr[arr2[j]] = 2;
}
}
}
return diffArr.keys();
}

JavaScript arrays - Finding the number of combinations of 2 elements

I come from a Ruby background, which features an enumerable class. In Ruby, I can easily find combinations of array elements.
array.combination(2).count
I know that JavaScript doesn't feature such built in functions, so I was wondering how I could implement this in JS. I was thinking something like
I have an array as follows
var numbers = [9,7,12]
var combos = []
for (var i = 0; i < numbers.length; i++) {
combos.push([numbers[i], numbers[i+1])
}
By the way, the possible combos are
[9,7], [9,12] and [7,12]
so by calling the length function on this array, 3 would be returned.
Any ideas?
How about:
for (var i = 0; i < numbers.length; i++)
for (var j = i + 1; j < numbers.length; j++)
combos.push([numbers[i], numbers[j]]);
Are you strictly talking about 2-combinations of the array or are you interested in a k-combinations solution?
Found this in this gist
function k_combinations(set, k) {
var i, j, combs, head, tailcombs;
if (k > set.length || k <= 0) {
return [];
}
if (k == set.length) {
return [set];
}
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
head = set.slice(i, i+1);
tailcombs = k_combinations(set.slice(i + 1), k - 1);
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
Here's a recursive function, which should work for any number:
function combination(arr, num) {
var r= [];
for(var i = 0 ; i < arr.length ; i++) {
if(num===1) r.push([arr[i]]);
else {
combination(arr.slice(i+1), num-1).forEach(function(val) {
r.push([].concat(arr[i], val));
});
}
}
return r;
} //combination
Working Fiddle

Categories