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);
Related
I have the following code below, the value that is being passed in is 4, 1, 9, 14, 6 ,8 and the
value which is assigned to newHeight is 1, 4, 6, 8, 9, 14. Insertion Sort sorts the array in ascending order.
var heightChecker = function(heights) {
var sorted = [...heights];
var newHeight = insertionSort(heights);
var count = 0;
for(var i = 0; i < newHeight.length; i++) {
if(newHeight[i] !== sorted[i]) {
count++;
}
}
return count;
}
insertionSort sorts the array, and when i use this line of code
var sorted = [...height];
Then it returns the answer I was looking for which is 3. However when i change the code to be
var heightChecker = function(heights) {
var newHeight = insertionSort(heights);
var count = 0;
for(var i = 0; i < heights.length; i++) {
if(newHeight[i] !== heights[i]) {
count++;
}
}
return count;
}
It returns the answer as 0.
I am not understanding why it isn't the same answer, and after debugging and google searching, I still cannot find why.
Here is the insertion sort code
function insertionSort(inputArr) {
let n = inputArr.length;
for (let i = 1; i < n; i++) {
// Choosing the first element in our unsorted subarray
let current = inputArr[i];
// The last element of our sorted subarray
let j = i-1;
while ((j > -1) && (current < inputArr[j])) {
inputArr[j+1] = inputArr[j];
j--;
}
inputArr[j+1] = current;
console.log(inputArr);
}
return inputArr;
}
a = [...b] creates a copy of b, a = b only assigns a different name to your value (i.e. a second reference pointing to the same value).
let a = [1,2,3];
b = a;
c = [...a];
a[1] = 41; // modifies value of a AND b
b[1] = 42; // modifies value of a AND b
c[1] = 43; // only modifies value of c
console.log(a); // 1, 42, 3
console.log(b); // 1, 42, 3
console.log(c); // 1, 43, 3
or, with a function call:
function addNumber(array, number) {
array.push(number);
}
let a = [1,2,3];
b = a;
c = [...a];
addNumber(b, 4); // now a = [1,2,3,4]; and b = [1,2,3,4] (=a); c = [1,2,3]
addNumber(c, 5); // still a = [1,2,3,4]; but c = [1,2,3,5]
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:
var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
array[i][j] = i * array[i].length + j;
}
}
The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise
Like explicit: array[ i ] [ j ] [ z ]= '.....code.....' using length property values and for-loops?
This is a recursive function that accepts an array that describes an n dimensions array, and populates it with consecutive numbers:
function makeNDArray(dims) {
var counter = 0;
function generateArr(dims) {
var arr = [];
var nextDims = dims.slice(1);
var hasNext = nextDims.length > 0;
for(var i = 0; i < dims[0]; i++) {
arr.push(hasNext ? generateArr(nextDims) : counter++);
}
return arr;
}
return generateArr(dims);
}
var result = makeNDArray([3, 5, 2]);
console.log(result);
And an ES6 version using Array#from to generate the arrays:
function makeNDArray(dims) {
let counter = 0;
const generateArr = (dims) => {
const nextDims = dims.slice(1);
const populate = nextDims.length > 0 ? () => generateArr(nextDims) : () => counter++;
return Array.from({ length: dims[0] }, populate);
}
return generateArr(dims);
}
const result = makeNDArray([3, 5, 2]);
console.log(result);
To populate your array you can use the folowing:
let x = 1
for (let i = 0; i < myArray.length; i++){
for (let j = 0; j < myArray[i].length; j++){
for (let k = 0; k < myArray[i][j].length; k++){
array[i][j][k] = x++ ;
}
}
}
If any of the dimensions are fixed, it's faster to hard code them:
for (var a = [], n = 0, i = 0, j, k; i < 5; i++)
for (j = 0, a[i] = []; j < 3; j++)
for (k = 0, a[i][j] = []; k < 2; k++)
a[i][j][k] = n++
console.log(JSON.stringify(a))
// faster
for (var a = [], n = 0, i = 0, j; i < 5; i++)
for (j = 0, a[i] = []; j < 3; j++)
a[i][j] = [n++, n++]
console.log(JSON.stringify(a))
// even faster
for (var a = [], i = 0, n = 0; i < 5; i++)
a[i] = [[n++, n++], [n++, n++], [n++, n++]]
console.log(JSON.stringify(a))
// fastest
var a = [[[0,1],[2,3],[4,5]],[[6,7],[8,9],[10,11]],[[12,13],[14,15],[16,17]],[[18,19],[20,21],[22,23]],[[24,25],[26,27],[28,29]]]
Otherwise, there are many shorter and slower ES6 alternatives (don't work in IE):
// nested:
var n = 0, a = [...Array(5)].map(v => [...Array(3)].map(v => [...Array(2)].map(v => n++)))
console.log(JSON.stringify(a))
var n = 0, r = c => [...Array(c)], a = r(5).map(v => r(3).map(v => r(2).map(v => n++)))
console.log(JSON.stringify(a))
var n = 0, r = (c, f) => [...Array(c)].map(f), a = r(5, v => r(3, v => r(2, v => n++)))
console.log(JSON.stringify(a))
// recursive:
var n = 0, r = (c, ...a) => [...Array(c)].map(v => a[0] ? r(...a) : n++), a = r(5, 3, 2)
console.log(JSON.stringify(a))
var n = 0, r = a => [...Array(a[0])].map(v => a[1] ? r(a.slice(1)) : n++), a = r([5, 3, 2])
console.log(JSON.stringify(a))
// recursive without having to declare n outside of the function:
var r = (a, n = [0]) => [...Array(a[0])].map(v => a[1] ? r(a.slice(1), n) : n[0]++), a = r([5, 3, 2])
console.log(JSON.stringify(a))
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
So, I am trying to figure out a situation where I would populate an array (b[]) with the index numbers from another array (a[]) whose elements meet a certain criteria (array b would be index numbers based on array a which is an array of images, and would populate b when width is greater than height).
So, I came up with a hypothetical function in hopes of getting an array output where I would get a listing from a[] that align with values from b[]. Needless to say, neither attempt came up with anything of value.
var a = ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi'];
var b = [2, 4, 5];
var d = function(a, b) {
var func1 = [];
var func2 = [];
for(i = 0; i > b.length; i++) {
func1.push(a[b[i]]);
}
console.log('func1 = ' + func1); // 'func1 = []'
for(i=0; i > a.length; i++) {
if(b.indexOf(a.indexOf(a[i])) > -1) {
func2.push(a[i])
}
}
console.log('func2 = ' + func2); // 'func2 = []'
}
d(a,b) // Ideally outputs ['cd', 'ef', 'fg']
Is this a matter of function scope, or am I missing the point of .push?
The comparisons in your for loops are backwards. They should be like this:
for(i = 0; i < b.length; i++) {
func1.push(a[b[i]]);
}
console.log('func1 = ' + func1); // 'func1 = []'
for(i=0; i < a.length; i++) {
if(b.index(a.indexOf(a[i])) > 1) {
func2.push(a[i])
}
}
Also, b.index is not a function. I assume you meant indexOf:
var a = ['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi'];
var b = [2, 4, 5];
var d = function(a, b) {
var func1 = [];
var func2 = [];
for(i = 0; i < b.length; i++) {
func1.push(a[b[i]]);
}
console.log('func1 = ' + func1); // 'func1 = []'
for(i=0; i < a.length; i++) {
if(b.indexOf(a.indexOf(a[i])) > 1) {
func2.push(a[i])
}
}
console.log('func2 = ' + func2); // 'func2 = []'
}
d(a,b) // Ideally outputs ['cd', 'ef', 'fg']
This outputs:
func1 = cd,ef,fg
func2 = fg
use for(i=0; i < a.length; i++) instead! Proper syntax is the key to success! Thanks #Superdrac
I have four arrays:
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
How to merge them into one json like string in Nodejs?
[{"a":1,"b":34,"c":22,"d":14},
{"a":2,"b":55,"c":23,"d":78},
{"a":3,"b":66,"c":53,"d":98}]
Here is my code, but anyone have a better solution? I do need preserve the quote.
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var obj = "[";
for (var u = 0; u < a.length; u++) {
var l = "\"a\":"+a[u]+",";
var m = "\"b\":"+b[u]+",";
var q = "\"b\":"+c[u]+",";
var n = "\"d\":"+d[u]+"";
if(u == (a.length-1))
var k = "{" + l + m + q + n + "}";
else
var k = "{" + l + m + q + n + "},";
console.log(k);
obj = obj + k;
};
obj = obj + "]";
console.log(obj);
Assuming all the arrays are the same length, and hardcoding their names:
var obj = []
for (var u = 0; u < a.length; u++) {
obj.push({
'a': a[u],
'b': b[u],
'c': c[u],
'd': d[u]
});
};
obj = JSON.stringify(obj);
EDIT: Converted the obj into a json string, the question had been mistakenly edited to ask for an array.
This piece of code will do the trick:
var arrays = [a, b, c, d]; // add all the arrays you want
var num = a.length; // or hardcode to the length you want
var result = [];
for(var i = 0; i < num; i++) {
var element = {};
attributes.forEach(function(attr, index) {
element[attr] = arrays[index][i];
});
result.push(element);
}
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var arrays = [a, b, c, d];
var result = [];
var num = a.length;
for(var i = 0; i < num; i++) {
var element = {};
attributes.forEach(function(attr, index) {
element[attr] = arrays[index][i];
});
result.push(element);
}
document.write(JSON.stringify(result));
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var x = [];
for (var i=0;i<3;i++) {
var obj = {};
for (var j=0;j<attributes.length;j++){
obj[attributes[j]]=eval(attributes[j]+"["+i+"]");
}
x.push(obj);
}
console.log(x);
I know there are multiple answers on this question already, but none seemed to handle the key arrays as variables who's names are introduced in the attributes array. Since I assumed that was the point of the attribute array, my solution does just that using node's global scope. It also does not assume that all the key arrays will be the same length as that is not specified (even though the example they are).
var attributes = ["a","b","c","d"];
var a = [1,2,3];
var b = [34,55,66];
var c = [22,23,53];
var d = [15,78,98];
var arr = [];
while(true){
var obj = {};
for(var i=0;i<attributes.length;i++){
if(global[attributes[i]].length)obj[attributes[i]]=global[attributes[i]].shift();
}
if(Object.keys(obj).length)
arr.push(obj);
else
break;
}
In the following fiddle, I had to emulate node's global scope by manually creating a global array, but you get the point:
Fiddle: https://jsfiddle.net/trex005/vm1yeL5d/
Important note If the arrays are not actually in the global scope, but are in some other object, you can use that object in place of global