This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 1 year ago.
I know this question has been asked before but all of the answers assume the array is a 2D array and only go one level deep.
I have a 4D array and have tried some of the solutions here and did not get the result. Here's my array:
I tried this answer from this question but this only goes one level deep. How do I make it work with a 4D array?
var newArray = [];
for (var i = 0; i < currentArray.length; i++)
newArray[i] = currentArray[i].slice();
You could use a simple recursive function that replaces arrays with copies after recursively handling its values:
function deepCopy(value) {
if (Array.isArray(value)) {
return value.map(deepCopy);
}
return value;
}
const data = [[[0]]];
const copy = deepCopy(data);
data[0][0][0] = 123;
console.log(data);
console.log(copy);
Actually looking at the bottom answers of that question, there are already (more complicated) deep copy functions present, such as this one. You can still use mine if you want a very simply only-deep-copies-arrays version of course.
Related
This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 4 years ago.
This how the default api returns. I want to sort them with basis of min_conversion_count properties.
After sorting the structure changes which is affecting my code. How is it possible to sort them with the property and remain the same format.
Code to sort
var rewarddata = res1.response.reward_list;
// console.log(rewarddata);
sortable_data = [];
console.log(rewarddata);
for (var idx in rewarddata)
{
sortable_data.push([idx,rewarddata[idx]]);
sortable_data.sort(function(a, b) {
return a[1].min_conversion_count - b[1].min_conversion_count;
});
console.log(sortable_data);
}
After sorting it changes like this.
You started out with an object, and you put it into an array in order to sort it; once your array is sorted, you have to turn it back into an object.
const sortedObj = sortable_data.reduce((accum, [key, value]) => {
accum[key] = value;
return accum;
}, {});
Note that property ordering is generally not something to rely on. It would be better to save an array of the sorted keys only, and then use that array instead.
This question already has answers here:
Are Javascript arrays sparse?
(7 answers)
Closed 6 years ago.
I was dealing with a problem and got to the point where I thought I could use the Ids to my entity instances as array indices for easy lookup.
var myArray = [];
myArray[obj.Id] = true;
Assume obj.Id is 1000 here, so will be myArray.length. Am I allocating 1000 bytes for a single boolean value here or is it just returning the maximum index as length?
It won't be allocating so many bytes.
But what you are really looking for is an key-value object like
var myObj = {};
myObj[obj.Id] = true;
//then to access
console.log(myObj[obj.Id])
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
It seems to me that one of the big downsides of javascript is that there are no associative arrays. Objects don't provide order, arrays don't provide keys.
There is also the possibility of arrays containing objects:
[{key1:value1}, {key2:value2}]
But as far as I know, there is no easy way to access elements by keys in this approach (without having to iterate through all elements).
That's why I started to think about the following approach, that is making an array associative by adding a element mapper:
Array.prototype.addKeyToLastElement = function(key) {
if (!this.elementMapper) this.elementMapper = {};
this.elementMapper[key] = this.length-1;
}
Array.prototype.getElementByKey = function(key) {
if (this.elementMapper && this.elementMapper[key] !== undefined) {
return this[this.elementMapper[key]];
}
else {
return undefined;
}
}
var test = [];
test.push(1);
test.addKeyToLastElement('a');
test.push(3);
test.addKeyToLastElement('b');
// get element by key
console.log(test.getElementByKey("a"));
I know that this is far from perfect, it's just a first try to see if it works. I was just wondering why I couldn't find any similar solutions.
Is this approach deprecated? If yes, what are the best alternatives?
My minimal requirements are:
Access elements by keys (retrieve/ alter value)
Maintain the elements order
Sort elements both by key and value
arrays don't provide keys
But as far as I know, there is no easy way to access elements by keys
in this approach (without having to iterate through all elements)
If interpret Question correctly, you could assign an alphabetic or other "key" as an index identifier and use a numeric identifier to access the same element within the array
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var arr = [];
for (var i = 0; i < alphabet.length; i++) {
arr[alphabet[i]] = arr[i] = alphabet[i]
};
console.log(arr["a"], arr[0], arr["z"], arr[25])
Is this approach deprecated? If yes, what are the best alternatives?
It is not deprecated, but it is not a good idea and hence a bad coding practice for following main reasons
These extra properties are not included in JSON serialisation.
These properties would be thrown away if you do an array operation like arr = arr.slice(1) which leads to un-expected behaviour.
But you can still sort the object like this (in your question)
[{key1:value1}, {key2:value2}]
by doing
var arr = [{key1:value1}, {key2:value2}];
arr.sort(function(a,b){
return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
})
This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
Closed 7 years ago.
I have an array of data which stores an object with functions and other such info. I push these objects to the function for my draw function to execute.
But i do not know of a way to find a specific object in an array to remove it and thus stop drawing it.
For example i have an array structure like this:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'something':'here'
};
var drawOrder= [];
drawOrder.push(data);
There are many functions in this array and they are pushed dynamically depending on what i wish to draw.
What would be the best way to find the index of one of these objects and remove it from the array in this case?
indexOf() returns the index in the array of the element you're searching for, or -1. So you can do:
var index = drawOrder.indexOf("aKey");
if (index != -1)
drawOrder.splice(index, 1);
Splice:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
indexOf:
http://www.w3schools.com/jsref/jsref_indexof_array.asp
I'm not 100% this will answer your question cause is not clear at least to me.
If you want to remove the whole element but you are worried about founding the right index before actually splice the array you should use Array.indexOF
See this code below:
var data = {
'fnc':function(){
updatePosition(spriteID);
drawSprite(spriteID);
},
'type':'aabb'
};
var drawOrder= [];
drawOrder.push(data);
console.log(drawOrder);
drawOrder.splice(drawOrder.indexOf(data), 1);
console.log(drawOrder);
As the documentation reports:
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Copying array by value in javascript
How to copy an array of objects to another array in Javascript?
var qwerty1 = arr;
var qwerty2 = arr;
Both qwerty1 and qwerty2 may look different but point to the same reference.
I read somewhere that "assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value." So my two arrays post different operations return the same objects.
Any light in this regard?
The idiomatic way to copy an array in Javascript is to use concat:
var qwerty1 = arr.concat();
var qwerty2 = arr.concat();