cloning a 2d array using JSON.stringify() - javascript

How are 2d arrays cloned using json.stringify and json.pasrse ?I came across this function which does but couldn't get the technique.What are some other methods to achieve the same?
Note: The JSON.stringify() method converts a JavaScript value to a JSON string.
let g2 = arrayclone(this.state.gridfull);// note gridfull is 2d array
function arrayclone(arr) {
return JSON.parse(JSON.stringify(arr));
}

You could use ES6 deestructurtig:
[...arr]
Or you could you Array.from:
Array.from(arr)
Or you could use concat:
[].concat(arr)
Or you could use slice:
arr.slice()
arr.slice(0)
You could create an empty array and iterate over your original one pushing elements to the new one.
I think that's pretty much it.
Hope it helps.

Related

Avoid using Object.values

df is an array of objects
I want to simplify this code, maybe the usage of Object.values could be redundant if I use another thing than map
Object.values(df.map(o => o.prop))
This piece of code returns an array of props.
Is it possible?
Unless df is a sparse array, the Object.values is totally redundant indeed.
df.map(o => o.prop)
already returns the same value as
Object.values(df.map(o => o.prop))

best way to flatten n-level array into 2d array

I know there are a lot of ways to flatten an array in javascript, but I want to know what's the best way to flatten an n-level array into a 2D array
Input array looks like this : [[[[1,2]]],[2,3]] i need to convert this into [[1,2],[2,3]]
I tried using array.flat() but it flattens only 1 step and I also tried array.flat(Infinity) but it flattens the whole array into 1D array
the problem is am not sure how deeply nested my input array is. I could think of iterating recursively but am looking if js has any optimised&ready-made way of achieving this?
You could combine map and flat(Infinity) methods to flatten each sub-array to 1D.
const flatDeep = data => data.map(e => e.flat(Infinity))
console.log(flatDeep([[[[1,2]]],[2,3]]))
console.log(flatDeep([[[[1,2]]],[2,[[[3, [4]]]]]]))
Iterate the array and then use Array.flat(Infinity) method.
const list = [[[[1,2]]],[2,3],[[3,4]]]
const result = [];
for (value of list) {
result.push(value.flat(Infinity));
}
console.log(result);

Reversing an array which is a value in object in Javascript

I am trying to reverse an array which is an element in an object.
colorKey = {
"2m":["#ffffff","#000000"]
}
colorKey["2mi"] = colorKey["2m"];
Array.reverse(colorKey["2mi"])
This is not working and returning colorKey["2mi"] the same as colorKey["2m"]. When I run the same command in developer console in browser, it reverses successfully. Where is the problem?
This is no static method off Array called reverse. reverse is an instance method (Array.prototype.reverse) off the Array object, so the instance of the Array must be the caller.
This solves your problem:
colorKey = {
"2m":["#ffffff","#000000"]
}
colorKey["2mi"] = colorKey["2m"];
colorKey["2mi"].reverse();
Output:
["#000000", "#ffffff"]
Calling reverse() for an array mutates it (reverse is in place - a new array is not created). What you want, apparently, is to have a reversed copy of the array. Basically, create a new array with the same values and then reverse it.
var a = [1, 2], b;
b = a.slice(0).reverse();
Slice creates a new array with the same elements (but remember that it is not cloning the elements).
#Rajat Aggarwal
What you are asking for, is to clone your previous array in reverse order.
The only trivial part of it would be reversing it. Because there is no way of cloning Objects and Arrays, nor a general method that you could write down as a function to be using it universally.
This specific array from the sample you provided can be cloned easily because it is flat and it only contains primitives. But the solution to it, will be exactly as specific as the sample array provided.
A specific solution to this task would be to use a plain coma-separated string of successive values and convert that to specific arrays of their corresponding primitive values.:
var colors = "#ffffff,#000000";
var colorKey = {
"2m":colors.split(","),
"2mi":colors.split(",").reverse()
}
which will yield you a:
>> colorKey
{
2m : #ffffff,#000000,
2mi : #000000,#ffffff
}

How can I convert a JavaScript object to an array

I have the following javascript object, in an array. I am using PHP's json_encode to get this value
[ { January=100}, { February=100} ]
I am trying to convert the following objects to
["January",100],["February",100]
I have searched around a lot and couldn't find an answer.
Any help would be really appreciated. Thanks!
Assuming you're trying to do this in Javascript, it can be done very easily using a library like Lodash:
server_array.map(_.toPairs)
Using native Javascript map function, with lodash's toPairs
Ignoring the incorrect syntax of your example javascript object code...
This is how to convert a javascript object to an array:
var newArray = []
for (var i in yourObject)
if(yourObject.hasOwnProperty(i))
newArray.push([i,yourObject[i]])
The above will yield the results your looking for.

Change the value of an array changes original array JavaScript

The following code causes both elements from id 0 to be set to -, even though I want only one to be set to -1. Am I just creating a reference to the labelArray, or is something else?
labelArray.sort(compare);
valueArray = labelArray;
valueArray[0] = '-1';
labelArray[0] = '-';
All help is appreciated.
UPDATE (2019): It's been several years since I first did this post, and ES6 is used pretty much universally. So, I wanted to come back and add that, instead of using the slice() method recommended in the accepted answer, you can instead use array destructing in the following to make a copy:
valueArray = [...labelArray];
Yes. Both valueArray and labelArray reference the same underlying array. To make a copy, use slice():
valueArray = labelArray.slice(0);
NOTE: Slice() only copies 1 level deep, which works fine for primitive arrays. If the array contains complex objects, use something like jQuery's clone(), credit #Jonathan.
Am I just creating a reference to the labelArray […] ?
Yes, exactly. valueArray and labelArray still identify the same object, which hasn't been copied.
valueArray is just a reference to labelArray.
What you want to do is clone the array. You can do this using jQuery.clone() or a similar cloning function.

Categories

Resources