JavaScript Add Values to Multidimensional Array - javascript

Hi I am trying to add some values to a multidimensional array using a for loop. This is what I have created so far:
var test1 = [];
var test2 = [];
for (var i = 0; i < top10.length; i++)
{
test1[i] = i;
test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];
}
This is just returning an empty array. top10 is a multidimensional array which contains:
It can contain more data that's why I need a for loop. I am trying to create 2 multidimensional arrays "test1" and "test2" one will contain "Hinckley Train Station" and "4754" the other will contain "Hinckley Train Station" and "2274".
I can have multiple venues not just "Hinckley Train Station" "4754" "2274" I could also have "London City" "5000" "1000". This is why it is a for loop.

You could push a new array to the wanted parts
var top10 = [
["Hinckley Train Station", "4754", "2274"],
["London City", "5000", "1000"]
],
test1 = [],
test2 = [],
i;
for (i = 0; i < top10.length; i++) {
test1.push([top10[i][0], top10[i][1]]);
test2.push([top10[i][0], top10[i][2]]);
}
console.log(test1);
console.log(test2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

In this line
test1[i] = i;
You are assigning an integer to be the first element of the outer array. You don't have a 2d array, you have an array of integers
In the following lines:
test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];
You are assigning properties to an integer, which means they are being boxed but the boxed value is thrown away.
It's hard to tell what you are trying to do, but the following is probably closer. You need to create a new inner array each time through the loop.
for (var i = 0; i < top10.length; i++)
{
test1[i] = [];
test1[i][0] = top10[i][0];
test1[i][1] = top10[i][1];
// Maybe do something similar with test2
}

Related

How to save the old state of an array before shuffling

I have an array of 50 objects as elements.
Each object contains an array of 4 elements:
var all = [{
question: "question 1 goes here",
options: ["A", "B", "C", "D"]
}, ... {
question: "question 50",
options: ["A", "B", "C", "D"]
}]
I want to select 10 elements randomly and save to two other arrays, one of the array I want to shuffle options. but when shuffling both arrays are affected.
var selected = [];
var shuffled = [];
for(let i = 0; i < 10; i++) {
let rand = Math.floor(Math.random() * all.length);
selected.push(all[rand]);
shuffled.push(all[rand]);
all.splice(rand, 1);
for(let j = 3; j > 0; j--) {
let rand2 = Math.floor(Math.random() * j);
[
shuffled[i].options[j],
shuffled[i].options[rand2]
] = [
shuffled[i].options[rand2],
shuffled[i].options[j]
];
}
}
console.log(selected); // is shuffled too
console.log(shuffled);
How do I prevent that?
I feel like I'm missing something pretty simple, but I can't spot it.
You need to create new instances for the chosen objects and their options arrays:
// shuffle array a in place (Fisher-Yates)
// optional argument len (=a.length):
// reduced shuffling: shuffling is done for the first len returned elements only,
// array a will be shortened to length len.
function shuffle(a, len=a.length){
for(let m=a.length,n=Math.min(len,m-1),i=0,j;i<n;i++){
j=Math.floor(Math.random()*(m-i)+i);
if (j-i) [ a[i],a[j] ] = [ a[j],a[i] ]; // swap 2 array elements
}
a.length=len;
return a;
}
const all=[...new Array(50)].map((_,i)=>({question:"Question "+(i+1), options:["A","B","C","D"]}));
const selected = shuffle([...all],10), // return first 10 shuffled elements only!
shuffled = selected.map(o=>({...o,options:shuffle([...o.options])}));
console.log(selected) // is no longer shuffled!
console.log(shuffled);
I consigned the shuffle algorithm to a separate function (shuffle()) and applied it twice: first to the all array to make sure we don't get any duplicates in our "random" selection and then to the options arrays contained within their sliced-off objects. The function shuffle(a,len) sorts array a in place. I made it return the array reference again purely out of convenience, as it helps me keep my code more compact. The optional argument len will cause the array a to be shortened to len shuffled elements (still "in place": the input array will be affected too!).
So, in order to preserve my "input" arrays I created new array instances each time I called the function by applying the ... operator:
shuffled = shuffle([...all],10);
...
shuffle([...o.options])
Try using the spread function that makes a hard copy from you object all
var selected = [];
var shuffled = [];
// Make a copy of all by using the spread function:
// You can later use this variable since it will contain the content of the
// initial all variable
const allCopy = [...all];
for (let i = 0; i < 10; i++) {
let rand = Math.floor(Math.random() * all.length);
selected.push(all[rand]);
shuffled.push(all[rand]);
all.splice(rand, 1);
for (let j = 3; j > 0; j--) {
let rand2 = Math.floor(Math.random() * j);
[shuffled[i].options[j], shuffled[i].options[rand2]] = [shuffled[i].options[rand2], shuffled[i].options[j]];
}
}
console.log(selected); // is shuffled too
console.log(shuffled);

Javascript - nested loops and indexes

I am trying to build an array that should look like this :
[
[{"name":"Mercury","index":0}],
[{"name":"Mercury","index":1},{"name":"Venus","index":1}],
[{"name":"Mercury","index":2},{"name":"Venus","index":2},{"name":"Earth","index":2}],
...
]
Each element is the concatenation of the previous and a new object, and all the indexes get updated to the latest value (e.g. Mercury's index is 0, then 1, etc.).
I have tried to build this array using the following code :
var b = [];
var buffer = [];
var names = ["Mercury","Venus","Earth"]
for (k=0;k<3;k++){
// This array is necessary because with real data there are multiple elements for each k
var a = [{"name":names[k],"index":0}];
buffer = buffer.concat(a);
// This is where the index of all the elements currently in the
// buffer (should) get(s) updated to the current k
for (n=0;n<buffer.length;n++){
buffer[n].index = k;
}
// Add the buffer to the final array
b.push(buffer);
}
console.log(b);
The final array (b) printed out to the console has the right number of objects in each element, but all the indexes everywhere are equal to the last value of k (2).
I don't understand why this is happening, and don't know how to fix it.
This is happening because every object in the inner array is actually the exact same object as the one stored in the previous outer array's entries - you're only storing references to the object, not copies. When you update the index in the object you're updating it everywhere.
To resolve this, you need to create new objects in each inner iteration, or use an object copying function such as ES6's Object.assign, jQuery's $.extend or Underscore's _.clone.
Here's a version that uses the first approach, and also uses two nested .map calls to produce both the inner (variable length) arrays and the outer array:
var names = ["Mercury","Venus","Earth"];
var b = names.map(function(_, index, a) {
return a.slice(0, index + 1).map(function(name) {
return {name: name, index: index};
});
});
or in ES6:
var names = ["Mercury","Venus","Earth"];
var b = names.map((_, index, a) => a.slice(0, index + 1).map(name => ({name, index})));
Try this:
var names = ["Mercury","Venus","Earth"];
var result = [];
for (var i=0; i<names.length; i++){
var _temp = [];
for(var j=0; j<=i; j++){
_temp.push({
name: names[j],
index:i
});
}
result.push(_temp);
}
console.log(result)
try this simple script:
var b = [];
var names = ["Mercury","Venus","Earth"];
for(var pos = 0; pos < names.length; pos++) {
var current = [];
for(var x = 0; x < pos+1; x++) {
current.push({"name": names[x], "index": pos});
}
b.push(current);
}

slice string to pieces and store each in new array

Help needed.
I have string like ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"] (unlimited number of pairs)
I need to make an array with pair like wT (as index) and WLw as value, for the whole string (or simpler wT as index0, WLw as index 1 and so on)
I'm trying to do it in JavaScript but I just cant figure out how to accomplish this task.
Much much appreciate your help!!
You cannot have a string as an index in an array, what you want is an object.
All you need to do is loop over your array, split each value into 2 items (key and value) then add them to an object.
Example:
// output is an object
var output = {};
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
If you wanted an array of arrays, then its much the same process, just pushing each pair to the output object
// output is a multidimensional array
var output = [];
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
output.push(source[index].split("="));
}
Update If your source is actually a string and not an array then you will have to do a little more splitting to get it to work
var output = {};
var sourceText = "[\"wt=WLw\",\"V5=9jCs\",\"7W=71X\",\"rZ=HRP9\"]";
// i have escaped the quotes in the above line purely to make my example work!
var source = sourceText.replace(/[\[\]]/g,"").split(",");
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
Update 2
If your desired output is an array of arrays instead of an object containing key-value pairs then you will need to do something like #limelights answer.
Object with Key-Value pairs: var myObject = { "key1": "value1", "key2": "value2" };
with the above code you can access "value1" like this myObject["key1"] or myObject.key1
Array of Arrays: var myArray = [ [ "key1", "value1"] ,[ "key2", "value2" ] ];
with this code, you cannot access the data by "key" (without looping through the whole lot to find it first). in this form both "key1" and "value1" are actually values.
to get "value1" you would do myArray[0][1] or you could use an intermediary array to access the pair:
var pair = myArray[0];
> pair == ["key1", "value1"]
> pair[0] == "key1"
> pair[1] == "value1"
You can use a for each loop on both types of result
// array of arrays
var data = [ [ "hello", "world"], ["goodbye", "world"]];
data.forEach(function(item) {
console.log(item[0]+" "+item[1]);
});
> Hello World
> Goodbye World
// object (this one might not work very well though)
var data = { "hello": "world", "goodbye": "world" };
Object.keys(data).forEach(function(key) {
console.log(key+" "+data[key]);
});
> Hello World
> Goodbye World
The normal for loop would do perfectly here!
var list = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
var pairs = [];
for(var i = 0; i < list.length; i++){
pairs.push(list[i].split('='));
}
This would give you an array of pairs, which I assume you want.
Otherwise just get rid of the outer Array and do list[i].split('=');
If you want it put into an object ie. not an Array
var pairObject = {};
for(var i = 0; i < list.length; i++){
var pair = list[i].split('=');
pairObject[pair[0]] = pair[1];
}

Objects within an Array

I have multiple objects like the one below, and I was wondering what the correct syntax would be for putting them all within a single array. I'm also wondering how to correctly cycle through all of the arrays.
var verbMap = [
{
infinitive: "gehen",
thirdPres: "geht",
thirdPast: "ging",
aux: "ist",
pastPart: "gegangen",
english: "go"
},
{
infinitive: "gelingen",
thirdPres: "gelingt",
thirdPast: "gelang",
aux: "ist",
pastPart: "gelungen",
english: "succeed"
}
];
I know the correct way to cycle through that above array is:
for(v in verbMap){
for(p in verbMap[v]){
}
}
If I wanted to cycle through a larger array holding multiple arrays like verbMap, what would be the correct way to do that?
Just put the verbMap arrays in another array.
var verbMaps = [verbMap1, verbMap2...]
The key thing to understand is that your verbMap is an array of object literals. Only use
for (k in verbMap)...
for object literals.
The correct way to loop thru an array is something like
for (var i = 0; i < verbMaps.length; i++) {
var currentVerbMap = verbMaps[i];
for (var j = 0; j < currentVerbMap.length; j++) {
var currentHash = currentVerbMap[j];
for (var k in currentHash) {
console.log(k, currentHash[k];
}
}
}
The following function outputs every value from a (possibly) infinite array given as a parameter.
function printInfiniteArray(value){
if (value instanceof Array){
for(i=0;i<value.length;i++){
printInfiniteArray(value[i]);
}
} else {
console.log(value);
}
}
Edited code. Thanks jtfairbank
Your array does not contain other arrays. It contains objects. You could try this to loop though it.
for(var i = 0; i < verbMap.length; i++)
{
var obj = verbMap[i];
alert("Object #"+ i " - infinitive: " + obj.infinitive);
}
You would treat the array like any other javascript object.
var arrayOfArrays = [];
var array1 = ["cows", "horses", "chicken"];
var array2 = ["moo", "neigh", "cock-adoodle-doo"];
arrayOfArrays[0] = array1;
arrayOfArrays[1] = array2;
You can also use javascript's literal notation to create a multi-dimentional array:
var arrayOfArrays = [ ["meat", "veggies"], ["mmmm!", "yuck!"] ];
To cycle through the array of arrays, you'll need to use nested for loops, like so:
for (var i = 0; i < arrayOfArrays.length; i++) {
var myArray = arrayOfArrays[i];
for (var j = 0; j < myArray.length; j++) {
var myData = myArray[0]; // = arrayOfArrays[0][0];
}
}
DO NOT USE For...in!!!
That is not what it was made for. In javascript, For...in can have some unwanted behaviors. See Why is using "for...in" with array iteration a bad idea? for more detail.
You can use jQuery.each to cycle through an array or object, without having to check which one it is. A simple recursive function to cycle through key-value pairs in a nested structure, without knowing the exact depth:
var walk = function(o) {
$.each(o, function(key, value) {
if (typeof value == 'object') {
walk(value);
} else {
console.log(key, value);
}
});
}

Group array items based on variable javascript

I have an array that is created dynamic from an xml document looking something like this:
myArray[0] = [1,The Melting Pot,A]
myArray[1] = [5,Mama's MexicanKitchen,C]
myArray[2] = [6,Wingdome,D]
myArray[3] = [7,Piroshky Piroshky,D]
myArray[4] = [4,Crab Pot,F]
myArray[5] = [2,Ipanema Grill,G]
myArray[6] = [0,Pan Africa Market,Z]
This array is created within a for loop and could contain whatever based on the xml document
What I need to accomplish is grouping the items from this array based on the letters so that all array objects that have the letter A in them get stored in another array as this
other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];
To clarify I need to sort out items based on variables from within the array, in this case the letters so that all array objects containing the letter A goes under the new array by letter
Thanks for any help!
You shouldn't use arrays with non-integer indexes. Your other variable should be a plain object rather than an array. (It does work with arrays, but it's not the best option.)
// assume myArray is already declared and populated as per the question
var other = {},
letter,
i;
for (i=0; i < myArray.length; i++) {
letter = myArray[i][2];
// if other doesn't already have a property for the current letter
// create it and assign it to a new empty array
if (!(letter in other))
other[letter] = [];
other[letter].push(myArray[i]);
}
Given an item in myArray [1,"The Melting Pot","A"], your example doesn't make it clear whether you want to store that whole thing in other or just the string field in the second array position - your example output only has strings but they don't match your strings in myArray. My code originally stored just the string part by saying other[letter].push(myArray[i][1]);, but some anonymous person has edited my post to change it to other[letter].push(myArray[i]); which stores all of [1,"The Melting Pot","A"]. Up to you to figure out what you want to do there, I've given you the basic code you need.
Try groupBy function offered by http://underscorejs.org/#groupBy
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
Result => {1: [1.3], 2: [2.1, 2.4]}
You have to create an empty JavaScript object and assign an array to it for each letter.
var object = {};
for ( var x = 0; x < myArray.length; x++ )
{
var letter = myArray[x][2];
// create array for this letter if it doesn't exist
if ( ! object[letter] )
{
object[letter] = [];
}
object[ myArray[x][2] ].push[ myArray[x] ];
}
Demo fiddle here.
This code will work for your example.
var other = Object.create(null), // you can safely use in opeator.
letter,
item,
max,
i;
for (i = 0, max = myArray.length; i < max; i += 1) {
item = myArray[i];
letter = myArray[2];
// If the letter does not exist in the other dict,
// create its items list
other[letter] = other[letter] || [];
other.push(item);
}
Good ol' ES5 Array Extras are great.
var other = {};
myArray.forEach(function(n, i, ary){
other[n[2]] = n.slice(0,2);
});
Try -
var myArray = new Array();
myArray[0] = [1,"The Melting Pot,A,3,Sake House","B"];
myArray[1] = [5,"Mama's MexicanKitchen","C"];
myArray[2] = [6,"Wingdome","D"];
myArray[3] = [7,"Piroshky Piroshky","D"];
myArray[4] = [4,"Crab Pot","F"];
myArray[5] = [2,"Ipanema Grill","G"];
myArray[6] = [0,"Pan Africa Market","Z"];
var map = new Object();
for(i =0 ; i < myArray.length; i++){
var key = myArray[i][2];
if(!map[key]){
var array = new Array();
map[key] = array;
}
map[key].push(myArray[i]);
}

Categories

Resources