var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr = arr.splice(4, 1)
console.log(arr)
//[5]
I want to remove only the last element. Why does it remove every element except the last one?
You need to omit the assignment.
var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]
arr.splice(4, 1);
console.log(...arr); // [1, 2, 3, 4]
If you like just to delete the last one, you could take a negative index with Array#splice. This works for any other index from the end.
var arr = [1, 2, 3, 4, 5]
console.log(...arr); // [1, 2, 3, 4, 5]
arr.splice(-1, 1);
console.log(...arr); // [1, 2, 3, 4]
Array#splice modifies the array in place and returns the removed portion. You should not reassign the removed portion to the variable.
var arr = [1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr);
splice alters the array and returns the removed item(s) in a new array.
By the way, you should use pop which is better suited for this like so:
var arr = [1, 2, 3, 4, 5];
arr.pop();
console.log(arr);
pop removes the last item of the array.
This is a more general approach:
var arr = [1, 2, 3, 4, 5]
arr.splice(arr.length - 1);
console.log(arr)
You can access to the last arr element by splice(-1), then you stored that value (5) into a variable (newArr). The original array now values [1, 2, 3, 4].
let arr = [1, 2, 3, 4, 5];
let newArr = arr.splice(-1);
console.log(arr) //[1, 2, 3, 4]
console.log(newArr) //[5]
The splice method takes two parameters: a beginning index (inclusive) and an ending index (exclusive). The below will do what you described.
arr = arr.splice(0, 4)
In your code, you are reassigning the arr to the spliced value, which is [5]. the way you should do it is,
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr)
//[1, 2, 3, 4]
This should give you the result you are looking for;
The splice() method adds/removes items to/from an array, and returns the removed items in the form of an array.
Syntax :
let arrDeletedItems = array.splice(starting_index , index to which you want to add or remove an item , item 1 , item 2 , item 3 ...so on )
let arr = [1, 2, 3, 4, 5]
arr.splice(4, 1)
so in your case, you are starting from index 4 which means the value "5" and you are removing the 1st element that starts from index 4 which is the value '5'. So the splice method would return a new array (as it returns a new array of the removed elements) containing only 5.
To get back an array containing all the elements except the last element 5 you should write :
arr = arr.splice(0,4)
which means that start from index 0 and remove elements till index 4.
Splice method returns the removed item(s) in an array so what is happening is you are assigning the returned to the original array. Instead do this
var arr = [1, 2, 3, 4, 5];
console.log(arr);
//[1, 2, 3, 4, 5]
arr.splice(4, 1);
console.log(arr);
Splice modifies array in place and returns removed part as a new array.
To get expected result you want to use expression:
var arr = [1, 2, 3, 4, 5]
console.log(arr)
//[1, 2, 3, 4, 5]
arr.splice(4, 1)
console.log(arr)
//[5]
You can also remove the last element from the array with rest operator
const array = [1, 2, 3, 4, 5]
const [ ...newArray, last ] = array
Related
Hello I'm new to javascript.
I was trying to reduce the length of an array by 1.
I did this, the last element is undefined now, but the length is still 5.
var arr = [1, 2, 3, 4, 5];
arr.length = arr.length--;
console.log(arr);
console.log(arr.length);
I'm confused. Instead of [1, 2, 3, 4] or [1, 2, 3, 4, 5]. Why it gives me [1, 2, 3, 4, undefined]?
Can someone explain? Thanks
arr.length-- will reduce the length by 1 already but will return the previous length, meaning you're reducing the array's length by 1 and then immediately assigning the previous length to arr.length, meaning you're changing it back to a five element array (but you already removed the fifth element ,so that's now undefined.
If you want to just reduce the array's length, you can user arr.length--; alone.
var arr = [1, 2, 3, 4, 5];
arr.length--;
console.log(arr);
console.log(arr.length);
You need to use array.prototype.pop you instead to reduce the size of your array:
var arr = [1, 2, 3, 4, 5];
arr.pop();
console.log(arr);
console.log(arr.length);
Take into consideration that arr.length-- with a length of 0 causes an error.
A timeline of what's happening in array.length = array.length--:
The -- operator changes array.length from 5 to 4.
array.length-- evaluates to the previous value of array.length, which is 5
This value is assigned to array.length, changing it from 4 to 5.
So you are shrinking the array and then growing it.
My advice: avoid mutating your arrays and instead use slice:
var arr = [1, 2, 3, 4, 5];
var newArr = arr.slice(0, -1);
console.log(newArr);
console.log(newArr.length);
If you insist on mutating your arrays, then I suggest you use a less mystifying operator: -=:
var arr = [1, 2, 3, 4, 5];
arr.length -= 1;
console.log(arr);
console.log(arr.length);
var arr = [1, 2, 3, 4, 5];
arr.splice(arr.length-1);
console.log(arr); //[1,2,3,4] --Expected Log
console.log(arr.length); //4 --Expected Log
Or you can try this:
var arr = [1, 2, 3, 4, 5];
arr.pop();
console.log(arr); //[1,2,3,4] --Expected Log
console.log(arr.length); //4 --Expected Log
if you want reduce , you can use 'splice'
I'm trying to swap the two lowest values in a shuffled array containing the numbers 0-14. For those curious, I'm implementing the shuffling algorithm for a 15 puzzle described by pkpnd here.
I wanted to try destructuring assignment, as described here, but am encountering an unexpected behavior. I realize that I can get my code working (and make it more readable) by just creating a temporary variable, but I'd like to understand what's happening before moving on.
I'm grabbing a subset of my array [1,2] and then trying to replace it with [2,1]. For some reason, it's only swapping the values when their order in the original array is opposite of the order of my subset.
I originally tried this:
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 3, 4];
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [arr1[arr1.indexOf(2)], arr1[arr1.indexOf(1)]];
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [arr2[arr2.indexOf(2)], arr2[arr2.indexOf(1)]];
console.log("arr1: " + arr1, "\narr2: " + arr2);
And then tried this:
var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 3, 4];
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [2, 1];
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [2, 1];
console.log("arr1: " + arr1, "\narr2: " + arr2);
But both produce identical output:
arr1: 1,2,3,4
arr2: 1,2,3,4
I would expect that the position of 1 and 2 would be swapped for both arrays, but they're only swapped in arr2. I suspect this has to do with they way the initial array subset [1,2] is created, but I'm not sure.
Can anybody explain why the values aren't always swapped?
The result is simple, because it goes step for step for each item of destructuring assingment. And while the values are changing, the index of the values changes.
Case 1 [1, 2, 3, 4]
Get index of target for the first value 2
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 0
Assign 2 to arr1[0]
[2, 2, 3, 4]
Get index of target for the second value 1:
[arr1[arr1.indexOf(1)], arr1[arr1.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 0
Assign 1 to arr1[0]
[1, 2, 3, 4]
Case 2 [2, 1, 3, 4]
Get index of target for the first value 2
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 1
Assign 2 to arr1[1]
[2, 2, 3, 4]
Get index of target for the second value 1:
[arr2[arr2.indexOf(1)], arr2[arr2.indexOf(2)]] = [2, 1];
// ^^^^^^^^^^^^^^^ 0
Assign 1 to arr1[0]
[1, 2, 3, 4]
How can I make a reversed copy of an array using .reverse()? I can't wrap my head around this.
This is my function:
function flipArray(inputArray){
let origArray = inputArray;
let flippedArray = origArray.reverse();
console.log(inputArray);
console.log(origArray);
console.log(flippedArray);
}
flipArray([1,2,3]);
I would expect this...
[1, 2, 3]
[1, 2, 3]
[3, 2, 1]
or this...
[1, 2, 3]
[3, 2, 1]
[3, 2, 1]
but this is what I get...
[3, 2, 1]
[3, 2, 1]
[3, 2, 1]
Why does even inputArray get reversed? Is there another way to do this apart from a for loop?
Array.prototype.reverse reverse the array in-place. It modifies the original array and returns a reference to it. In order to create copies of the original array before it is reversed, you could use Array.prototype.slice, for example:
function flipArray(inputArray){
let origArray = inputArray.slice(0);
let flippedArray = inputArray.slice(0).reverse();
console.log(inputArray);
console.log(origArray);
console.log(flippedArray);
}
flipArray([1,2,3]) now produces
[1,2,3]
[1,2,3]
[3,2,1]
Basic question on .splice() method, and how best to remove an element from an array.
I want to remove an item from an array with .splice() but when I do, I want to have the original array minus the removed element returned. .splice() returns the removed element instead.
var arr = [1, 2, 3, 4, 5, 6, 7]
var newArr = arr.splice(3, 1)
console.log(newArr) // [4]
// whereas I want [1, 2, 3, 5, 6, 7]
What's the best, and most eloquent way to do this?
Using the spread operator, you can do:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [
...arr.slice(0,indexToRemove),
...arr.slice(indexToRemove+1)
]
Or if you want to use ES5, it can look something like:
var arr = [1,2,3,4,5,6],
indexToRemove = 3,
newArr = [].concat(arr.slice(0,indexToRemove)).concat(arr.slice(indexToRemove+1))
.splice mutates the array in place and returns the removed elements. So unless you actually need a function that returns the array itself, just access arr:
var arr = [1, 2, 3, 4, 5, 6, 7]
arr.splice(3, 1)
console.log(arr) // [1, 2, 3, 5, 6, 7]
You can create a wrapper function that performs the splice and returns the array:
function remove(arr, index) {
arr.splice(index, 1)
return arr;
}
var newArr = remove(arr, 3);
// Note: `newArr` is not a new array, it has the same value as `arr`
If you want to create a new array, without mutating the original array, you could use .filter:
var newArr = arr.filter(function(element, index) {
return index !== 3;
}); // [1, 2, 3, 5, 6, 7]
arr; // [1, 2, 3, 4, 5, 6, 7]
I need to check if all items in an array can be found within another array. That is, I need to check if one array is a subset of another array.
Example:
var array = [1, 2, 5, 7];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
Comparing these two arrays above should return true as all items in array can be found in otherArray.
var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
Comparing these two arrays above should return false as one of the items in array cannot be found in otherArray.
I have tried to use the indexOf method inside a for loop without success.
I hope someone could help me. :)
Use Array.prototype.every:
The every() method tests whether all elements in the array pass the test implemented by the provided function.
var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];
var isSubset = array.every(function(val) {
return otherArray.indexOf(val) >= 0;
})
document.body.innerHTML = "Is array a subset of otherArray? " + isSubset;