JavaScript scope: preserve object in array in function [duplicate] - javascript

This question already has answers here:
How to copy JavaScript object to new variable NOT by reference? [duplicate]
(2 answers)
Closed 3 years ago.
I am using .map() on an array inside a function. I am not modifying the array itself (arr = arr.map(...)), but rather creating a new array (var arr2 = arr.map(...)).
Yet, this still modifies the original arr outside my function (which I don't want). How can I preserve?
var arr = [{prop: 1}];
myFunction(arr);
console.log(arr[0].prop); // returns 2, I want it to return 1
function myFunction(arr) {
var arr2 = arr.map(obj => {
obj.prop = 2;
return obj;
});
console.log(arr[0].prop); // returns 2
}

It modifies based on its reference. If you want to create a new object and modify its properties then you need to use Spread Syntax. Read the documentation:
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
You can try the following:
var arr = [{prop: 1}];
myFunction(arr);
function myFunction(arr) {
var arr2 = arr.map(obj => {
let copyObj = {...obj};
copyObj.prop = 2;
return copyObj;
});
console.log(arr[0].prop);
console.log(arr2[0].prop);
}

Related

How to merge two arrays to make an object [duplicate]

This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Closed 1 year ago.
consider i have an array say
let arr1=["john","Bruce","Clent"];
and
let arr2=[55,33,22];
Then how can i make an object out of this in javascript
object should look like:{"john":55,"Bruce":33,"Clent":22};
it should take arr1 as object's keys and arr2 as object'values
You can just loop the array, but use the index to match the key and value.
const arr1=["john","Bruce","Clent"];
const arr2=[55,33,22];
const obj = {};
arr1.forEach((val, i) => {
obj[val] = arr2[i];
});

How to remove dublicate values from array of objects using javaScript? [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));

Javascript Grammer: how to assign correct values to an array of objects [duplicate]

This question already has answers here:
new Array(_).fill(object) does not create new instances of object [duplicate]
(5 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Closed 2 years ago.
let's look at the code:
Test() {
let array1 = new Array(5).fill({ a: 0 })
let array2 = new Array(5).fill({ a: 0 })
for (let i = 0; i < 5; i++) {
setTimeout(() => {
array1[i].a = i
array2[i] = {a:i}
console.warn("array = ", array1)
console.warn("array2 = ", array2)
}, 0.2 * i)
}
}
In this case, I wanna assign a series of values to the array1 & array2, and there are two ways to do it, which lead to totally different results.
In the case array1[i].a = i, after all the code is ran, the result is array = [{a:4},{a:4},{a:4},{a:4},{a:4}], which is not what i wanted.
In the second case array2[i] = {a:i}, the result will be [{a:0},{a:1},{a:2},{a:3},{a:4}] as expected.
I wanna know why is it like this? What's the machanics behind this phenomenon?
Thank you.
When you call .fill() and pass an object, you assign the exact same object to every element of the array. Thus, modifying a property at one array index modifies the same property at all the other indexes, because they're all pointing to the same thing.
There are a variety of ways around this issue. You could fill the array with 0 or null or some dummy value and then iterate through with .forEach(), or more simply just use an indexed for loop to initialize each element. If you initialize with { a: 0} in a for loop, a new object will be created on each iteration.

JavaScript matrix wired behaviour when using new Array() [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.

Weird behaviour in Array.fill [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.

Categories

Resources