+ 1
JS: arr.sort() does not work a second time
I need to remove from arr1 the elements in position defined by arr2. Now I need to add elements from arr3 to arr1, then to sort them by value, from lowest to highest. But .sort() does not work a second time. See link: https://code.sololearn.com/W5S05R2Xr3i5
4 Answers
+ 1
Matteo
The problem is in startoo3() you are using push() to add the elements of arr3 to arr1, but what is actually happening is that arr3 is being pushed onto arr1 as one whole array instead of the seperate elements of arr3.
https://code.sololearn.com/WagMP2rmmiqU/?ref=app
Try concat()
https://www.w3schools.com/jsref/jsref_concat_array.asp
+ 1
Matteo
You are very welcome.
But I believed I may have misled you somewhat due to the mistake in the code I submitted, please take another look at it. I commented on line 24 where the mistake was made.
To be clear concat() will return a new array but arr1 = arr1.concat(arr3) will produce the same results as the loop you are using. The difference is that concat() is more concise and readable.
+ 1
OLDNT
So basically with the arr1 = arr1.concat(arr3) the code is creating a new array and immediately replacing with arr1, effectively producing the same result.
Well thanks again that's defenitely more practical and readable.
0
OLDNT
Thank you so much for the answer and expecially for adding the console.log wich helped me undertand immediately what you meant.
I didn't want to use the concat() method cause if I'm not mistaken it creates a new array and I'll need to reference arr1 multiple times during the rest of the code.
So I simply made another for loop to push elements into arr1 one by one.
https://code.sololearn.com/WAM2Jw73i3Zo