Related
I have an array and I want to swap two elements in the array. If the array is non-empty, I can simply do:
const swap = (arr, a, b) => {
const temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
}
and the function can correctly swap the value of the index a and b in the array arr.
However, if the array has some empty elements, such as [1, , , ,], and the result of the swap will be [undefined, empty, 1, empty], while the expected result should be [empty × 2, 1, empty]. So how do I modify the swap function so that the result will be correct. Or is there any way to make a specific index to be empty in an array?
Also failed:
const swap = (arr, a, b) => {
const temp = arr[a]
arr.splice(a, 1, arr[b])
arr.splice(b, 1, temp)
}
Original Problem:
I have an array let arr = [1, , , ,] (which will show [1, empty × 3] in console) with length 4, and I want to move the first element to the third, that is: [empty × 2, 1, empty]. How do I achieve that?
I have tried splice and directly assign value to the array but they won't work.
You do need splice - combined with shift to get the first item
let arr = [1, , , ,]
console.log(arr)
arr.splice(2, 0, arr.shift());
console.log(arr)
I have a 2 dimensional array, with integers, and all what I want is to increment a particular item with a number.
The initial state:
var arr1=[];
var arr2=[1,2,3];
arr1.push(arr2);
arr1.push(arr2);
arr1.push(arr2);
arr1 now looks like this:
0:[1, 2, 3]
1:[1, 2, 3]
2:[1, 2, 3]
What I want is to increment the [0,0] element of this array with 10, so arr1 should be:
0:[11, 2, 3]
1:[1, 2, 3]
2:[1, 2, 3]
What I did:
arr1[0][0]+=10;
But this way the result is:
0:[11,2,3]
1:[11,2,3]
2:[11,2,3]
What am I missing? Why increments this command all the numbers at position 0 of the array elements?
Because every element of arr1 is the same array, so a change to one is a change to all.
Try this:
var arr1=[];
arr1.push([1,2,3]);
arr1.push([1,2,3]);
arr1.push([1,2,3]);
arr1[0][0]+=10;
That will give you the desired result.
Your issue is that you've got the same reference to an object three times and when you change that object's value, all references to that object will display the updated value.
When you run var arr2=[1,2,3];, It will instantiate an object and assign it to arr2.
When you run arr1.push(arr2), you are pushing a reference to that object assigned to arr2.
In other words, arr1[0] === arr1[1] === arr1[2].
What you need to do is
var arr1=[];
arr1.push([1,2,3]);
arr1.push([1,2,3]);
arr1.push([1,2,3]);
That is happening because you are not pushing a copy of arr2 into arr1, but a reference (pointer) to arr2, which means that you are editing the same array over again.
To avoid that, you should be using spread.
Instead of arr1.push(arr2) do arr1.push([...arr2])
Here is a JSFiddle with output:
0: Array(3) [ 11, 2, 3 ]
1: Array(3) [ 1, 2, 3 ]
2: Array(3) [ 1, 2, 3 ]
When you assign an array to a variable, you are not making a copy of the array.
let arr1 = [1,2,3];
let arr2 = arr1; // This does NOT create a copy of the array!
console.log(arr1[0]);
arr2[0] = "BOOM!"; // change arr2
console.log(arr1[0]); // displays "BOOM!" not 1 - arr1 is changed, too!
This is because both arr1 and arr2 are pointing to the same array.
Objects (Arrays are Objects too) are passed as references. That means that your array looks like this (pseudostructure):
arr2 -> [1, 2, 3]
arr1 -> [ -> arr2, -> arr2 -> arr2]
Therefore arr1[0] is just the same as arr1[1] or arr2. To create three different arrays copy the array:
arr1.push([...arr2]);
I have an initial array,
I've been trying to change values (orders) by using pop, splice methods inside a for loop and finally I push this array to the container array.
However every time initial array is values are pushed. When I wrote console.log(initial) before push method, I can see initial array has been changed but it is not pushed to the container.
I also tried to slow down the process by using settimeout for push method but this didnt work. It is not slowing down. I guess this code is invoked immediately
I would like to learn what is going on here ? Why I have this kind of problem and what is the solution to get rid of that.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial);
}
return schedulePattern;
}
**Console.log**
(4) [1, 2, 3, 4]
(4) [1, 4, 2, 3]
(4) [1, 3, 4, 2]
(3) [Array(4), Array(4), Array(4)]
0 : (4) [1, 3, 4, 2]
1 : (4) [1, 3, 4, 2]
2 : (4) [1, 3, 4, 2]
length : 3
When you push initial into schedulePattern, it's going to be a bunch of references to the same Array object. You can push a copy of the array instead if you want to preserve its current contents:
schedulePattern.push(initial.slice(0));
Good answer on reference types versus value types here: https://stackoverflow.com/a/13266769/119549
When you push the array to schedulepattern, you are passing a reference to it.
you have to "clone" the array.
use the slice function.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial.slice());
}
return schedulePattern;
}
You have to know that arrays are mutable objects. What does it mean? It means what is happening to you, you are copying the reference of the object and modifying it.
const array = [1,2,3]
const copy = array;
copy.push(4);
console.log(array); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3, 4]
There are a lot of methods in Javascript which provide you the way you are looking for. In other words, create a new array copy to work properly without modify the root.
const array = [1,2,3]
const copy = Array.from(array);
copy.push(4);
console.log(array); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
I encourage you to take a look at Array methods to increase your knowledge to take the best decision about using the different options you have.
//code1
let a= [1, 3 , 4, 6];
[7, 8 , 9].forEach(l => a.push(l));
console.log(a);
// [1, 3, 4, 6, 7, 8, 9 ]
1.it worked for push() function
//code2
let a= [1, 3 , 4, 6];
a.forEach(l => a.pop(l));
console.log(a);
//[ 1, 3 ]
2. didn't work for pop() though
Javascript Array.pop() removes the last element from the array and returns that.
Example:
var arr = [1,2,3]
arr.pop(); // returns 3
Reference
If you want to remove a element with specific value than try something like:
var arr = [1, 2, 3];
var index = arr.indexOf(1);
if (index > -1) {
array.splice(index, 1);
}
var arr = [1, 2, 3, 4];
console.log(arr.pop());
var index = arr.indexOf(2);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr)
forEach automatically extracts the elements one by one and gives them to you
It starts from the beginning of the array, and does them all.
It doesn't delete elements from the array.
a = [1, 3, 4, 6];
a.forEach(item => console.log(item));
// output is in forwards order
// and 'a' retains original contents
pop() extracts and deletes one element for you
It starts from the end of the array, and does only one.
It deletes the element from the array.
a = [1, 3, 4, 6];
while (a.length > 0) {
console.log(a.pop())
}
// items come out in reverse order
// and 'a' is being emptied so it is [] at the end
Choose your method
Do you want the last element actually removed from the array? This is what you would want if you were implementing a stack, for example. In that case, use ".pop()".
This gets one element from the end of the array and deletes it from the array.
Or do you want to just look at each element in turn from the array (starting at the beginning), without changing the array itself. This is a commoner situation. In this case, use ".forEach"
This is what I'm trying to do, I have an array
var arr = [1, 2, 3, 4, 5];
then I want to create a new array each time by removing an item once i.e when i remove item at index 0 i should have [2, 3, 4, 5]and when i remove an item at index 1, I should have [1, 3, 4, 5] and so on till i get to arr.length-1 and each time i remove an item i still want my arr to be intact unchanged
using javaScript I have tried some array methods like splice, slice but all that changes the value of arr
how do i go about it with either javascript or python.
For Javascript, using ES6 array spread operator and slice method,
var new_array = [...a.slice(0, index), ...a.slice(index + 1)];
const cut = (a, i) => [...a.slice(0, i), ...a.slice(i + 1)];
let arr = [2, 2, 2, 4, 2];
console.log(cut(arr, 3));
console.log(arr);
For Python:
array = [1,2,3,4,5];
newarray = [value for counter, value in enumerate(array) if counter != 0 ]
PS each time you will use this list-comprehension, array will not be modified! so basically you will get the same output for newarray.
If you want to have newarray each time removed one element you need to create a function instead of list-comprehension (of course it's possible but will likely be less readable).
For JavaScript:
Try making a copy with slice() (slice returns a shallow copy of the array that you can manipulate without affecting the original array) and then using splice() to remove the value at your desired index:
newArray = slice(arr).splice(index, 1);