Spread syntax doesn't work to destructive an array - javascript

I am new to Javascript and is confused why the following won't work?
var array = [1, 2, 3, 4]
var spread = ...array;
I was expecting it would become 1, 2, 3, 4. Instead, it gave an error message Unexpected token .... Can anyone explain this to me?
Thank you so much!

This is the correct way, however you're not gaining anything doing that.
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);
If you really want to destructure that array, you need destructuring assignment:
var array = [1, 2, 3, 4]
var [one, two, three, four] = array;
console.log(one, two, three, four);

The correct way of doing what you want is:
var array = [1, 2, 3, 4]
var spread = [...array];

The syntax for using spread is:
For function calls:
myFunction(...iterableObj);
For array literals or strings:
[...iterableObj, '4', 'five', 6];
For object literals (new in ECMAScript 2018):
let objClone = { ...obj };
So, based on the syntax, for an array by using spread you are missing the square brackets []:
var array = [1, 2, 3, 4]
var spread = [...array];
console.log(spread);

Related

Problem with Accesing array data Javascript

I want to access data of var a so it is: 245 but instead it only accesses the last one. so if i print it out it says 5
var A = [1, 2, 3, 4, 5];
var B = A[[1], [3], [4]];
console.log(B)
When accessing an object using square bracket notation — object[expression] — the expression resolves to the string name of the property.
The expression [1], [3], [4] consists of three array literals separated by comma operators. So it becomes [4]. Then it gets converted to a string: "4". Hence your result.
JavaScript doesn't have any syntax for picking non-contiguous members of an array in a single operation. (For contiguous members you have the slice method.)
You need to get the values one by one.
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B.join(""))
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B)
You'll need to access A multiple times for each index.
var A = [1, 2, 3, 4, 5];
var B = A[1];
console.log(A[1], A[3], A[4])
You can access them directly like that.
If you want to access index 2 for example, you should do console.log(A[1]);
You can't access multiple indices at the same time.
A variable can have only one value.
#Quentin solution resolve the problem, I wrote this solution to recommend you to create an array of index, and iterate over it.
Note: You are getting the last index, because you are using the comma operator. The comma operator allows you to put multiple expressions. The resulting will be the value of the last comma separated expression.
const A = [1, 2, 3, 4, 5];
const indexes = [1,3,4];
const B = indexes.map(i => A[i]).join``;
console.log(B);

Trying to create copies of an array using spread operator, but some how the array is being mutated

I'm trying to practice with the concept of immutability. I'm using the the spliceTest array as my main reference for creating copies of the array and mutating those. I'm coming to the problem when I declare removeOneItem variable, I somehow can't declare a new spread variable using the same reference of spliceTest.
const removeOneItem = [...spliceTest.splice(0,0), ...spliceTest.splice(1)];
const removeFive = [...spliceTest.splice(0,4), ...spliceTest.splice(5)];
const spreadTest = [...spliceTest];
console.log('removeOneItem:', removeOneItem)
console.log('spreadTest:', spreadTest, spliceTest)
console.log('removeFive:', removeFive)
Results::::::::::::
removeOneItem: [ 2, 3, 4, 5, 6, 7, 8, 9 ]
spreadTest: [] []
removeFive: [ 1 ]
According to MDN:
The splice() method changes the contents of an array by removing or
replacing existing elements and/or adding new elements in place.
This means, that the splice operation changes your array
Immutability of data is a cornerstone of functional programming and in general I'll do what you are trying to do: clone the data and mutate the clone. The following function takes an array and a series of sub-arrays. The sub-arrays consist of [startIndex, quantity]. It clones the original array by the spread operator and splices the clone according to the second parameter (...cutDeep). It will return an object with the original array and the cloned array. If you wrap everything in a function then your scope protects each return. Note on subsequent turns The second clone (secondResult.dissected) is spliced once more and the last log proves the original array is never mutated.
Demo
const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
const dissect = (array, ...cutDeep) => {
let clone = [...array];
for (let [cut, deep] of cutDeep) {
clone.splice(cut, deep);
}
return {
original: array,
dissected: clone
};
}
const firstResult = dissect(data, [2, 3], [5, 2], [9, 1]);
const secondResult = dissect(data, [3, 2], [10, 1]);
console.log(JSON.stringify(firstResult));
console.log(JSON.stringify(secondResult));
console.log(JSON.stringify(dissect(secondResult.dissected, [0, 2], [5, 1])));
console.log(JSON.stringify(data));
The problem is that you use splice when you most likely want to use slice.
splice is used for mutating an array, while slice is used to select a sub-array.
const sliceTest = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// select a sub-array starting from index 1 (dropping 0)
const removeOneItem = sliceTest.slice(1);
// select a sub-array starting from index 5 (dropping 0, 1, 2, 3, and 4)
const removeFive = sliceTest.slice(5);
// spread the full array into a new one
const spreadTest = [...sliceTest];
// array log helpers (leave these out in your code)
const toString = array => "[" + array.join(",") + "]";
const log = (name, ...arrays) => console.log(name, ...arrays.map(toString));
log('removeOneItem:', removeOneItem)
log('spreadTest:', spreadTest, sliceTest)
log('removeFive:', removeFive)
slice already creates a shallow copy of the array, so [...arr.slice(i)] is not needed.

How to combine array within another array using javascript or jquery?

I have an array named arr and within that array, I have another array.My question is, how to combine this two array?
var arr=["1","2","[3,4]","5"]
My output should be like this:
1,2,3,4,5
Thanks in advance!
You could use spread syntax ... with map and JSON.parse methods.
var arr = ["1","2","[3,4]","5"]
var result = [].concat(...arr.map(e => JSON.parse(e)))
console.log(...result)
Considering that you have an actual array and not a string you can flatten like this
var arr=["1","2",["3","4"],"5"]
var flat = [].concat(...arr)
console.log(flat)
You can change it to string and further replace the square brackets using replace(/[\[|\]]/g,''):
var arr=["1","2","[3,4]","5"];
var res = arr.toString().replace(/[\[|\]]/g,'');
console.log(res);
If the question is how to flat an array like this [1,2,[3,4],5] or this [1,[2,[[3,4],5]]] into this[ 1, 2, 3, 4, 5 ] here a pretty general and short solution:
var arr = [1, [2, [[3, 4], 5]]];
var newArr = JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
console.log(newArr)
Or .flat if browser supports it:
var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
console.log(arr)

Deep copy Javascript array with properties

Using .slice(), I can deep copy a Javascript Array of primitive types, for example:
var arr = [1,2,3,4];
var newArr = arr.slice();
newArr.push(5);
console.log(arr); // [1,2,3,4]
console.log(newArr); // [1,2,3,4,5]
However, If I add a property to arr like so:
arr.prop1 = 5;
and do the same:
var arr = [1,2,3,4];
arr.prop1 = 8;
arr.prop2 = 9;
var newArr = arr.slice();
newArr.push(5);
console.log(arr); // [1, 2, 3, 4, prop1: 9, prop2: 8]
console.log(newArr); // [1, 2, 3, 4, 5]
The property values do not carry over to newArr
I have considered not using .slice() and looping over the property values of arr instead, assigning them to newArr, using :
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
newArr[key] = arr[key];
}
}
console.log(arr); // [1, 2, 3, 4, prop1: 9, prop2: 8]
console.log(newArr); // [1, 2, 3, 4, 5, prop1: 9, prop2: 8]
Is this going to be the quickest way to deep copy these arrays with properties? Is there in easier or cleaner way I can do this using .slice() or another array method? I am doing this operation tens of thousands of times and want it to be as clean and efficient as possible
You are trying to mix an array and object(to make an array behave like an object).
JavaScript array has numeric indexed items.
JavaScript object has string indexed items.
Arrays have a length property that tells how many items are in the array and is automatically updated when you add or remove items to the array.But ...
var arr = [1,2,3,4], newArr = arr.slice();
arr.prop1 = 7;
console.log(arr.length);
The output is 4, though you would expect it to be 5.But arr.prop1 = 7 does not actually add to the array.Setting a string parameter adds to the underlying object.
The length property is only modified when you add an item to the array, not the underlying object.The expression newArr = arr.slice() assigns a new array to newArr, so it remains an array and behaves like a pure array.
The property values do not carry over to newArr
If you still want to proceed using mixed numeric/string indexed sequences, cloning them, try using Object.assign() function. This should be the easiest way for your case:
The Object.assign() method is used to copy the values of all
enumerable own properties from one or more source objects to a target
object.
console.log(Object.assign(newArr, arr));
The output:
[1, 2, 3, 4, prop1: 7]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
How about using Object.create(proto)
var arr = [1,2,3,4];
arr.prop1 = 8;
arr.prop2 = 9;
var newArr = Object.create(arr);
newArr.prop1 = 12;
console.log(arr.prop1) // 8
console.log(newArr.prop1) // 12
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

localStorage and Javascript Object with arrays, save Issue

I have the follwoing Components:
patientDiseasesStorage = new Object()
patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number
I try now to save this Object/Array Combination
localStorage.setItem('patientDiseasesStorage', JSON.stringify(patientDiseasesStorage));
But when i try to read this back from localStorage it does not have the correct values:
patientDiseasesStorage = JSON.parse(localStorage.getItem('patientDiseasesStorage'));
patientDiseasesStorage['p158246547'] is now undefined and not the array.
What am I doing wrong?
If p158246547 is a string and not a variable name, it should have quotes around it:
patientDiseasesStorage['p158246547'] = [1, 3, 8, 2, 5] //and many more of this with different p-number
Use the quotes when you pull it back out of the localStorage as well.
What browser are you using? Latest Chrome works for me.
var a = [1, 2,3]
var obj = {'a': a}
obj.a
> [1, 2, 3]
localStorage.setItem('obj', JSON.stringify(obj))
var obj2 = JSON.parse(localStorage.getItem('obj'))
obj2.a
> [1, 2, 3]

Categories

Resources