Javascript array becomes null - javascript

I defined two-dimensional array, tried to fill it in nested loop, but it fill only first dimension with right values, other dimensions are filled with null(or undefined), thanks.
var Arr = [];
var i =0;
for(i=0;i<13;i++)
{
Arr[i]=[];
}
var a=0,b=0;
for(a=0;a<13;a++)
{
for(b=0;b<13;b++)
{
Arr[[a][b]]=AnotherArrWithRightValues[(13 * a) + b];
}
}

Arr[[a][b]] should be Arr[a][b]

Loksly's answer is correct, but implemented in a different way. To answer your question, replace Arr[[a][b]] with Arr[a][b].
Full Code :
var Arr = [];
for(var a = 0 ; a < 13 ; a++) {
Arr[a] = [];
for(var b = 0 ; b < 13 ; b++) {
Arr[a][b]=AnotherArrWithRightValues[(13 * a) + b];
}
}

Just for the record, another way to achieve the same:
var Arr = [];
var i = 0, tmp;
var a, b;
for(a = 0; a < 13; a++){
tmp = [];
for(b = 0; b < 13; b++){
tmp.push(AnotherArrWithRightValues[i++]);
}
Arr.push(tmp);
}

Try this,
var arr =[];
for(var a=0;a<13;a++)
{
arr[a] = new Array();
for(var b=0;b<13;b++)
{
arr[a].push((13 * a) + b);
}
}
i hope this will help you

Related

How to create array for loop

I want to create a array like this:
[{'b':0,'c':1,'d':2},{'b':1,'c':2,'d':3},{'b':2,'c':3,'d':4}]
How can I do this in Javascript?
I have tried this:
for(i = 0; i < 3; i++){
var b = i;
var c = i+1;
var d = i+2;
};
dataResult={"b":b,"c":c,"d":d};
alert(dataResult) //not working result [{'b':0,'c':1,'d':2},{'b':1,'c':2,'d':3},{'b':2,'c':3,'d':4}]
You are just overriding value of 'b','c','d' and at the end assigning that value to 'dataResult', so you are not getting expected result.
Try this.
dataResult = [];
for(i = 0; i < 3; i++){
dataResult.push({ 'b': i, 'c': i+1, 'd': i+2 });
};
console.log(dataResult);
You'll have to create the object inside the loop, and then push it to the array:
const arr = [];
for (let i = 0; i < 3; i++) {
var b = i;
var c = i + 1;
var d = i + 2;
arr.push({ b, c, d });
}
console.log(arr);
But it would be a bit more elegant to use Array.from here:
const arr = Array.from({ length: 3 }, (_, i) => {
const b = i;
const c = i + 1;
const d = i + 2;
return { b, c, d };
});
console.log(arr);
Create the object inside the loop and push it to an array
var arr = [];
for (var i = 0; i < 3; i++) {
let obj = {
b: i,
c: i + 1,
d: i + 2,
}
arr.push(obj)
};
console.log(arr)
var myArr = [];
for(var i = 0; i < 3; i++){
var data = i;
myArr.push({
b: data,
c: data + 1,
d: data + 2
})
}
console.log(myArr)
You were creating the object outside the loop. You need to create object inside the loop.
Try following
var arr = [];
for(let i = 0; i < 3; i++){
var b = i;
var c = b+1; // as b = i, you can change c = b + 1
var d = c+1; // as c = i + 1, you can change d = c + 1
arr.push({b,c,d});
};
console.log(arr);
You are setting the value of b, c, d after it loops so it puts the latest value of b, c, d in dataResult. Instead, you should initialize dataResult with an empty array and push values to the array after every step of the loop
var a,b,c;
var dataResult = [];
for(i = 0; i < 3; i++){
b = i;
c = i+1;
d = i+2;
dataResult.push({"b":b, "c":c, "d":d});
};
alert(dataResult);

Infinity loop with generating random numbers?

I'm working on a script that creates random mathematical problems (simple questions). The problem is that there seems to be an infinite loop, and I can't figure out where or how my script can run without this part of the code.
https://codepen.io/abooo/pen/GyJKwP?editors=1010
var arr = [];
var lastArr = [];
while(lastArr.length<122){
arr.push('<br>'+Math.round(Math.random() * 10)+'+'+Math.round(Math.random() * 10)+'=');
lastArr=removeDuplicates(arr);
}
document.write(lastArr.join(' '));
alert(arr.length);
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
This is the working snippet without any infinity loop.
var arr = [];
while(arr.length < 121){
var randValue = '<br>'+Math.round(Math.random() * 10)+'+'+Math.round(Math.random() * 10)+'='
arr.push();
// Check duplicate elements before push
if ( arr.indexOf(randValue) == -1 ) arr.push(randValue);
}
document.write(arr.join(' '));
alert(arr.length);
It looks like you are trying to shuffle every possible outcome of adding two numbers from 0 to 10. Why not do that, rather than your attempt of "throw missiles into pidgeonholes and hope for the best"?
function generateArray(maxA, maxB) {
var arr = [],
a, b;
for (a = 0; a <= maxA; a++) {
for (b = 0; b <= maxB; b++) {
arr.push([a, b]);
}
}
return arr;
}
function shuffleArray(arr) {
// simple Fisher-Yates shuffle, modifies original array
var l = arr.length,
i, j, t;
for (i = l - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
function outputArray(arr) {
var i, l = arr.length;
for (i = 0; i < l; i++) {
document.write("<br />" + arr[i][0] + " + " + arr[i][1] + " = ");
}
}
var arr = generateArray(10, 10);
shuffleArray(arr);
outputArray(arr);
The line Math.round(Math.random() * 10) will give you 11 possible outcomes (from 0 to 10). That means there are 11*11 non-duplicates lastArr can hold.
As mentioned in the comments, it does not only take a long time for every possibility to occur, it is also impossible for lastArr to be longer than 121 (11*11), which means your loop cannot end, due to the condition while(lastArr.length<122).
Besides that there are better ways to achieve the desired result, changing your code to this will make it work:
var arr = [];
var lastArr = [];
while(lastArr.length<121){ // Here I change 122 to 121
arr.push('<br>'+Math.round(Math.random() * 10)+'+'+Math.round(Math.random() * 10)+'=');
lastArr=removeDuplicates(arr);
}
document.write(lastArr.join(' '));
alert(arr.length);
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}

Javascript: Given an array, return a number of arrays with different ordered combinations of elements

I need code that takes an array, counts the number of elements in it and returns a set of arrays, each displaying a different combination of elements. However, the starting element should be the same for each array. Better to explain with a few examples:
var OriginalArray = ['a','b','c']
should return
results: [['a','b','c'], ['a','c','b']]
or for example:
var originalArray = ['a','b','c','d']
should return
[['a','b','c','d'], ['a','b','d', 'c'], ['acbd', 'acdb', 'adbc', 'adcb']]
Again note how the starting element, in this case 'a' should always be the starting element.
You can use Heap's algorithm for permutations and modify it a bit to add to result only if first element is equal to first element of original array.
var arr = ['a', 'b', 'c', 'd']
function generate(data) {
var r = [];
var first = data[0];
function swap(x, y) {
var tmp = data[x];
data[x] = data[y];
data[y] = tmp;
}
function permute(n) {
if (n == 1 && data[0] == first) r.push([].concat(data));
else {
for (var i = 0; i < n; i++) {
permute(n - 1);
swap(n % 2 ? 0 : i, n - 1);
}
}
}
permute(data.length);
return r;
}
console.log(generate(arr))
You have to do a .slice(1) to feed the rest of the array to a permutations function. Then you can use .map() to stick the first item to the front of each array in the result of permutations function.
If you will do this job on large sets and frequently then the performance of the permutations function is important. The following uses a dynamical programming approach and to my knowledge it's the fastest.
function perm(a){
var r = [[a[0]]],
t = [],
s = [];
if (a.length <= 1) return a;
for (var i = 1, la = a.length; i < la; i++){
for (var j = 0, lr = r.length; j < lr; j++){
r[j].push(a[i]);
t.push(r[j]);
for(var k = 1, lrj = r[j].length; k < lrj; k++){
for (var l = 0; l < lrj; l++) s[l] = r[j][(k+l)%lrj];
t[t.length] = s;
s = [];
}
}
r = t;
t = [];
}
return r;
}
var arr = ['a','b','c','d'],
result = perm(arr.slice(1)).map(e => [arr[0]].concat(e));
console.log(JSON.stringify(result));

JavaScript stable sort issue

I've looked around for some help on this topic but was unable to find some help or guidance.
My problem is I am attempting to perform a sort on a series of values separated by an equals sign.
"Foo=Bar , Shenanigans=Fun, A=B ...etc"
My current sort works, but only if no value is the same. If I have some values like:
"Foo=Bar, A=Bar, Potato=Bar"
When the sort is complete they will all be "A=Bar"
My current sort looks like this, would someone be able to point me in the right direction?
$('#sortByValue').click(function() {
var textValueArray = document.getElementById('nameValuePairList');
textArray = new Array();
valueArray = new Array();
oldValues = new Array();
for (i = 0; i < textValueArray.length; i++) {
valueArray[i] = textValueArray.options[i].value;
textArray[i] = textValueArray.options[i].text;
oldValues[i] = textValueArray.options[i].value;
}
valueArray.sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
for (i = 0; i < textValueArray.length; i++) {
textValueArray.options[i].value = valueArray[i];
for (j = 0; j < textValueArray.length; j++) {
if (valueArray[i] == oldValues[j]) {
textValueArray.options[i].text = textArray[j];
j = textValueArray.length;
}
}
}
});
I know that my problem lies here: valueArray[i] == oldValues[j]
as when the data comes in valueArray = {Bar, Foo, Bar} while textArray = {Foo=Bar, A=Foo, Test=Bar}
However, I am unsure how to best resolve it.
Sort textArray directly, don't use valueArray since it will contain duplicates:
textArray.sort(function(a,b){
var aa = a.split('=')
var bb = b.split('=')
var a_key = aa[0].toLowerCase(), a_val = aa[1].toLowerCase();
var b_key = bb[0].toLowerCase(), b_val = bb[1].toLowerCase();
if (a_val == b_val) return a_key.localeCompare(b_key);
return a_val.localeCompare(b_val);
})
I would do something like this:
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = [];
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a !== "" && b !== ""){
return a.split('=')[0].localeCompare(b.split('=')[0]);
} else {
return 0;
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
Take a look at this demo
The reasoning behind doing this at all will have you wondering why, in the future. I think you want something like this:
function inArray(v, a){
for(var i=0,l=a.length; i<l; i++){
if(a[i] === v){
return true;
}
}
return false;
}
function sortWeirdString(str){
var pairs = str.split(/\s?,\s?/), n = [], v = [], c = [], ci, idx = [], cl, nv = [], ra = [];
for(var i=0,l=pairs.length; i<l; i++){
var pair = pairs[i].split(/\s?=\s?/);
n.push(pair[0]); v.push(pair[1]);
}
c = n.concat().sort(); cl = c.length
for(var i=0; i<cl; i++){
var cv = c[i];
if(n.indexOf){
ci = n.indexOf(cv);
if(inArray(ci, idx)){
ci = n.indexOf(cv, ci+1);
}
idx.push(ci);
}
else{
for(var x=0; x<cl; x++){
if(n[x] === cv){
if(inArray(x, idx)){
continue;
}
idx.push(x);
}
}
}
}
for(var i=0,l=idx.length; i<l; i++){
ra.push(c[i]+'='+v[idx[i]]);
}
return ra.join(', ');
}
$('#sortByValue').click(function(){
console.log(sortWeirdString($('#nameValuePairList').val()));
}
Update 2019
The spec has changed and #Array.prototype.sort is now a stable sort.
The elements of this array are sorted. The sort must be stable (that
is, elements that compare equal must remain in their original order)
This is already implemented in V8

Multiplying all numbers in two arrays in javascript

As an exercise, I'm trying to create a function that returns the palindromic numbers resulting from multiplying three-digit numbers. As far as I can tell, the function is running through numbers correctly, however, the resulting array is incorrect. I don't need the solution to the palindrome problem...just an idea of what I might be missing. Have I run into some limitation?
var palindromic = function() {
var a = [];
var res = [];
for (var i = 100; i < 1000; i++) {
a.push(i);
}
var ar = a.slice(0);
a.map(function(x) {
for (var j = 0; j < ar.length; j++) {
var result = x * ar[j];
if (result.toString() === result.toString().split("").reverse().join("")) {
res.push(result);
}
}
})
return res;
};
Pretty sure it's just trying to call console.log() 810,000 times. If you comment the console.log line, it works just fine.
var palindromic = function() {
var a = [];
var res = [];
for (var i = 100; i < 1000; i++) {
a.push(i);
}
var ar = a.slice(0);
a.map(function(x) {
for (var j = 0; j < ar.length; j++) {
var result = x * ar[j];
//console.log(x + " : " + ar[j] + ' = ' + result);
if (result.toString() === result.toString().split("").reverse().join("")) {
res.push(result);
}
}
});
return res;
};
console.log(palindromic());

Categories

Resources