I am trying to test if my deep clone of an array is identic to the original object (jQuery available).
Here is how I clone it
self.slides = jQuery.extend(true, {}, parent.modules[self.moduleId].composed);
However, I end up with two slightly different objects, so even if the actual content that I am concerned with is identic, these two objects aren't. If I dump them in chrome console, this is how they look:
Original object:
[Object]
0: Object
length: 1
__proto__: Array[0]
Clone:
Object {0: Object}
0: Object
__proto__: Object
So the clone appears to actually be an object (or an object of type object) while the original seem to be an array (or object of type array).
Is there another way of cloning or how can I perform this identic-test?
Simplest way to clone any object would be
var array1 = [1, [2], 3];
var array2 = JSON.parse(JSON.stringify(array1));
You can check them like this
console.log(array1, array2);
// [ 1, [ 2 ], 3 ] [ 1, [ 2 ], 3 ]
array1[1][0] += 3;
console.log(array1, array2);
// [ 1, [ 5 ], 3 ] [ 1, [ 2 ], 3 ]
this occurs because you are passing an object "{}" extender to try to clone this way, I believe it is much better
var clone = myArray.slice(0);
Related
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' ] ]
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}
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])
I have an array of JSON-like object[Object,Object...] (I was calling it array of JSON object until I see this ) and I would like to go through each item in it. The JSON object has 3 values {name:"name",date:"2015-01-01",c:3} in it and I want to put each of them into a new array. Should I use a for item in JSONArary{item = ...} or for (i=0,i<len,i++){array[i] = ....} or should I JSONArray.pop()? Which one is faster and why? What if I want to reverse the array? Do reversing cost a lot?
for (i=0,i<len,i++){array[i] = ....} should be faster than for item in JSONArary{item = ...} because the later will traverse all enumerable properties on this object, while some of these properties are unnecessary.
When you want to iterate over just the indexed properties of an array, the only guaranteed way to keep things semantically consistent is to use an integer index.
For your reference: Why is using "for...in" with array iteration a bad idea?
Even Google make the JavaScript coding style guide as:
for-in loop: Only for iterating over keys in an object/map/hash
I have a faster way, use $.map:
var oldArray = [{
name: "name1",
date: "2015-01-01",
c: 3
}, {
name: "name2",
date: "2015-01-01",
c: 3
}, {
name: "name3",
date: "2015-01-01",
c: 3
}];
var newArray = $.map(oldArray, function (item) {
return {
FullName: item.name,
RegisterDate: item.date
};
});
alert(JSON.stringify(newArray));
Hope this help.
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.