Convert a simple array to a two dimensional array of objects - javascript

I want to convert this:
[null, 1890, null, NGU]
...into this:
[[], [1890], [], [NGU]]
I've tried creating a new array and pushing values to it, but that just ends up looking the same. Honestly, I'm unsure of what to even call what I'm trying to create. Is it a two-dimensional array or an array of objects?
This is for a google app script and the documentation calls it a two-dimensional array of values.

var arr = [null, 1890, null, 'NGU']
var arr2d = arr.map(x => [x])
console.log(arr2d) // output --> [ [ null ], [ 1890 ], [ null ], [ 'NGU' ] ]

Related

JavaScript Array.push() duplicating across multiple (nested) arrays [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 1 year ago.
Recently, I was trying to create three-level deep nested arrays. Crazy, I know, but it was the best solution to my problem I could think of. The arrays are created with the following code.
const lengths = [2, 3];
const arrays = lengths.map((v, i) => {
return Array(lengths[i]).fill([]);
});
arrays[0][0].push(1);
console.log(arrays);
// Expected: [ [ [ 1 ], [] ], [ [], [], [] ] ]
// Actual: [ [ [ 1 ], [ 1 ] ], [ [], [], [] ] ]
As you can see, I only push to array[0][0]. Yet, both [0][0] and [0][1] get pushed to. What is going on here? Is it a bug, or a feature? Some kind of weird memory management?
If it helps, I am using Node.js. Thanks in advance.
You are filling the entire array with the same array reference. Instead, you could use the mapping callback of Array.from to rectify this issue by returning a different array each time.
const lengths = [2, 3];
const arrays = lengths.map((v, i) => {
return Array.from({length: lengths[i]}, _=>[]);
});
arrays[0][0].push(1);
console.log(arrays);
.as-console-wrapper{top:0;max-height:100%!important}

How do you tap the key of this object?

I'm working on a project for myself (gotta keep busy). I have JavaScript that taps API, and retrieves data as follows:
{
'2020-12-18:95': {
'45.0': [ [Object] ],
'50.0': [ [Object] ],
'55.0': [ [Object] ],
'60.0': [ [Object] ]
}
}
How do I enumerate through that? When I
object.2020-12-18:95
to get to the strike prices, I get error mesg. Your help is appreciated 😀
You can try using Object.keys() and .map() to iterate through as:
const data = {
'2020-12-18:95': {
'45.0': [ {} ],
'50.0': [ {} ],
'55.0': [ {} ],
'60.0': [ {} ]
}
}
const result = data['2020-12-18:95']
Object.keys(result)
.map(key => console.log(key, result[key]))
From the documentations:
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

How to map an array to another array and reset its keys in Javascript?

I have an object that has unique keys and each key holds an object:
var object = { 'a': {
source: '5279edf0-cd7f-11e3-af07-59475a41e2e9',
target: 'f6b3faa1-ad86-11e3-9409-3dbc47429e9f',
id: [ 'bf504d02-81e2-4a92-9c5c-8101943dc36d' ],
edge_context: [ 'small' ],
statement_id: [ '09b05bc0-20ab-11e9-a5b3-9fb3da66a7cb' ],
weight: 2
},
'b': {
source: '5279edf1-cd7f-11e3-af07-59475a41e2e9',
target: 'f6b3faa1-ad86-11e3-9409-3dbc47429e9f',
id: [ 'de769846-9145-40f8-ab2d-91c0d9b82b27',
'd5723929-71a0-4dfe-bf03-94d43e358145' ],
edge_context: [ 'small' ],
statement_id:
[ '09b05bc0-20ab-11e9-a5b3-9fb3da66a7cb',
'62671510-20ab-11e9-8cbf-ef11fdb08712' ],
weight: 6
}
}
var newArray = [];
for (let item of object) {
newArray(item);
}
console.log(newArray);
I want to map it to another array where the keys will be in a sequence 0, 1, 2 etc as the usual array
I tried to use this function above but it's not working saying "object is not iterable" so how to iterate the object?
Maybe:
const mappedObject = Object.keys(object).map(
k => object[k]
)
As others have pointed out, change the structure. It could be in the following way (you will obtain an array of objects, which you will be able to access using indexes like 0, 1, 2, etc):
var objt = [
{"a": {
"source": "5279edf0-cd7f-11e3-af07-59475a41e2e9",
"target": "f6b3faa1-ad86-11e3-9409-3dbc47429e9f",
"id": [ "bf504d02-81e2-4a92-9c5c-8101943dc36d" ],
"edge_context": [ "small" ],
"statement_id": [ "09b05bc0-20ab-11e9-a5b3-9fb3da66a7cb" ],
"weight": 2
}
},
{"b": {
"source": "5279edf1-cd7f-11e3-af07-59475a41e2e9",
"target": "f6b3faa1-ad86-11e3-9409-3dbc47429e9f",
"id": [ "de769846-9145-40f8-ab2d-91c0d9b82b27",
"d5723929-71a0-4dfe-bf03-94d43e358145" ],
"edge_context": [ "small" ],
"statement_id":
[ "09b05bc0-20ab-11e9-a5b3-9fb3da66a7cb",
"62671510-20ab-11e9-8cbf-ef11fdb08712" ],
"weight": 6
}
}
];
var newArray = objt.map(element => {
const firstProperty = Object.keys(element)[0];
let objectInfo = element[firstProperty];
console.log(objectInfo);
return objectInfo;
});
console.log(newArray);
What happens here is, the only field of each object is not named the same (in one object is "a", the next one is "b", and so on) so we need to figure out to get the only property of each object in the initial array, which contains the information you need to put in another array. For doing this. Object.keys() returns you an array of the properties of an object. Considering the scenario in which we only have one property per object, we get it using Object.keys(element)[0].
Finally, we just use .map() to generate a new array.
I would use Object.values(object) but it's not supported by IE (there is a polyfill for that). Or would use Object.getOwnPropertyNames (which is supported by IE) to convert the keys to an array and map the array to another which containing the values.
var newArray = Object.getOwnPropertyNames(object).map(key => object[key])

Difference between Array(n) and [...Array(n)]

Why there is a difference in map() output in the below code?
var y = [1,2,2,1];
var t = y.map(ind => [...Array(ind)].map((_,i) => ind+""+i));
// This makes [ [ '10' ], [ '20', '21' ], [ '20', '21' ], [ '10' ] ]
var t1 = y.map(ind => Array(ind).map((_,i) => ind+""+i));
//[ [ <1 empty item> ], [ <2 empty items> ], [ <2 empty items> ], [ <1 empty item> ] ]
This is basically the reason you should avoid using the Array constructor to create arrays.
When passed a single number n as an argument, the Array constructor will return an array with length n, but no elements, also known as a sparse array. (Anything else passed to the Array constructor, a string, an object, two numbers, etc, will create a normal array with the passed arguments as elements in order).
Trying to .map() over this array will not work, since there are no items in it, which is why you get the same sparse arrays. Your .map() is a no-op.
Using [... (Same with Array.from(), by the way) on it, will "realize" the array turning [ <1 empty item> ] into [undefined] and [ <2 empty items> ] into [undefined, undefined], an array with actual elements, whose values are undefined. .map() does work on this, so you get the result you expect.
In short, avoid the Array constructor.

Array structure / syntax (turns out the real q was about classes, didn't know the term.)

is my understanding of arrays inside of arrays is built like this?
a = new Array[
b = new Array[
c = new Array[
something,
something.more,
something.more.to,
something.more.to.learn
]]];
or does it need to be
a = new Array[];
a.b = new Array[];
a.b.c = new Array[
a.b.c.something,
a.b.c.something.more,
a.b.c.something.more.to,
a.b.c.something.more.to.learn
];
or am I as lost as I think I am.
You need to differentiate between arrays and objects.
You may use arrays like so:
var nested = new Array(
new Array( '1.1', '1.2' ),
new Array( '2.1', '2.2' ),
);
Or use the short syntax:
var nested = [ [ '1.1', '1.2' ], [ '2.1', '2.2' ] ];
But you can't access array items by a textual index like in PHP or the like, you need to refer to the numbered index to call the different elements.
// Alert the first value of the second array in nested.
// Note that array indeces start off on zero.
alert( nested[ 1 ][ 0 ] ); // -> 2.1
If you need to reference the different elements you have to use objects:
var nested = {
first: {
a: '1.1',
b: '1.2'
},
second: {
a: '2.1',
b: '2.2'
}
}
alert( nested.second.a ); // -> 2.1
You can define multi-dimensional arrays a couple different ways but if you want inline, this would be a very simple way. (This is just a random structure for example purposes)
var arr =
[
["a"],
[
["b"],
[],
[
["c"]
]
],
[
[],
[]
]
];
Things get really hard to follow but just treat each tab in as a sub dimension of the parent array.
To access any element you would use indexes
arr[0][0]; // "a"
arr[1][0][0]; // "b"
arr[1][2][0][0]; // "c"
This really helps when you have intracate structures where delcaring new Array(...) would get very chained and complicated.

Categories