Related
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
Here's a sample of the problem I'm having in JavaScript:
first array [1, 2, 3, 4, 5, 6, 7]
second array [7, 8, 9, 4, 2, 5, 7]
In this case, I need to be able to find and eliminate "4" and "7" from both arrays, eliminating both. This is based on their location and matching value.
I haven't been able to find anything other than eliminating matching values. In this case, however, the values must be in the same place and also be matching.
I've tried this so far:
function findCommonElements3(array1, array2) {
return arr1.some(item => arr2.includes(item))
}
it looks like it only looks for matching elements, whereas I need to find matching corresponding elements and then remove them.
As mentioned in the comments, you may use the splice method to remove one or more elements of an array in JavaScript.
First of all I would store the indexes of the elements I should remove looping the array as so:
const array1 = [1, 2, 3, 4, 5, 6, 7];
const array2 = [7, 8, 9, 4, 2, 5, 7];
//Indexes of same elements
var sameIndexes = [];
function findSameIndexes(element, index) {
if (array1[index] == array2[index]) {
sameIndexes.push(index);
}
}
array1.forEach(findSameIndexes);
Calling console.log(sameIndexes) should give this result:
Array [3, 6]
The problem is that if you loop again the array and remove the elements in that order, the indexes would not correspond to the elements anymore.
For example if you remove the 3rd element, the number 7 wouldn't be at index 6 anymore, to solve this issue I'd use the reverse method so you won't lose track of the indexes
// A simple function to remove the elements in both arrays
function removeElements(index) {
array1.splice(index,1);
array2.splice(index,1);
}
sameIndexes.reverse().forEach(removeElements);
And the final results would be
Array [1, 2, 3, 5, 6]
Array [7, 8, 9, 2, 5]
Which hopefully is what you were looking for, of course there are better ways to write it down, but maybe this will help you find a solution.
You could just use a for loop and use index. something like this
const firstarray = [1, 2, 3, 4, 5, 6, 7]
const secondarray = [7, 8, 9, 4, 2, 5, 7]
for (let i = 0; i <= firstarray.length - 1; i++) {
if (firstarray[i] === secondarray[i]) {
console.log(`found ${firstarray[i]} at index ${i}`);
firstarray.splice(i, 1);
secondarray.splice(i, 1);
}
}
console.log(firstarray, secondarray);
const excludeCommon = (ar1, ar2) => {
const both = [...ar1, ...ar2].filter((v, i, ar) => v !== ar[i + (2 * (i < ar1.length) - 1) * ar1.length]);
return [both.slice(0, both.length / 2), both.slice(both.length / 2)];
}
console.log(excludeCommon([1, 2, 3, 4, 5, 6, 7], [7, 8, 9, 4, 2, 5, 7]));
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 have a bunch of arrays, eg:
var myArrayName = [1, 2, 3, 4, 5, 6];
var myArrayName2 = [1, 2, 3, 4, 5, 6];
var myArrayName3 = [1, 2, 3, 4, 5, 6];
In my DOM I have elements with data-name="myArrayName" data-push="7", data-name="myArrayName2" data-push="2" etc.
I want to select all the elements with data-name and then push data-push values to them, so:
$("*[data-name]").each(function(){
var arName = $(this).data("name");
var toPush = $(this).data("push");
// how do I make the stuff below work?
// arName.push(toPush);
})
This would select all the elements with the attribute data-name
var arrDataAttr = new Array();
var arrDataPush = new Array();
$(document).find("[data-attr]").each(function()
{
arrDataAttr.push($(this).attr("data-attr"));
arrDataPush.push($(this).attr("data-push"));
});
You need to use an object ( dictionary, map, whatever you call it ):
var arrays = {
'myArrayName': [],
'myArrayName2':[],
'myArrayName3':[]
}
$("*[data-name]").each(function(){
var arName = $(this).data("name");
var toPush = $(this).data("push");
arrays[arName].push(toPush);
})
An easy way to do this could be to wrap all the arrays under an object to namespace them:
var arrays = {
myArrayName: [1, 2, 3, 4, 5, 6];
myArrayName2: [1, 2, 3, 4, 5, 6];
myArrayName3: [1, 2, 3, 4, 5, 6];
};
Then, you can access the arrays by their name, like this:
// to access the first array:
arrays["myArrayName"];
The final code looks like this:
$("[data-name]").each(function(){
var $item = $(this);
var arName = $item.data("name");
var toPush = $item.data("push");
arrays[arName].push(toPush);
});
Notes:
Please note that I'm caching the $(this) variable, if you want to know why, check this
If you want to know more about accessing object properties with JavaScript, check this
Try adjusting names of array variables , data-* attribute , using $.each() called on arrays , select element having data-name ending with current index of loop
var myArrayName0 = [1, 2, 3, 4, 5, 6];
var myArrayName1 = [1, 2, 3, 4, 5, 6];
var myArrayName2 = [1, 2, 3, 4, 5, 6];
$.each([myArrayName0, myArrayName1, myArrayName2], function(index, arr) {
arr.push($("[data-name$=" + index + "]").data("push"))
});
console.log(myArrayName0, myArrayName1, myArrayName2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div data-name="myArrayName0" data-push="7"></div>
<div data-name="myArrayName1" data-push="2"></div>
<div data-name="myArrayName2" data-push="1"></div>
I normally use while loop as:
while (i<some_value)
I saw while(i--) syntax and thought it is shorter and cooler and tried the following in google-chrome.
var num_arr= [4,8,7,1,3];
var length_of_num_arr=num_arr.length;
while(length_of_num_arr--) console.log(num_arr);
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3]
[4, 8, 7, 1, 3] **// THIS IS EXPECTED RESULT**
But When I try...
while((num_arr.length)--) console.log(num_arr);
[4, 8, 7, 1]
[4, 8, 7]
[4, 8]
[4]
[] // WHY IS THIS HAPPENING??
Is there some hidden things you need to understand to use this syntax?
Arrays’ length property is writable, and will cut off their elements or add empty slots as appropriate when you set it.
var items = [1, 2, 3, 4, 5];
items.length = 3; // items is now [1, 2, 3]
items.length = 6; // items is now a sparse array: [1, 2, 3, undefined × 3]
So, don’t do that.
When you do array.length-- you're potentially shortening the array by one element each time.
See the reference under the section Shortening the array from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Array.prototype.length can be re-written programmatically and it potentially shorten your array by the new length you assign.
For example
a = [1,2,3,4,5,6,7,8,9,10];
// Shorten the array by one element
a.length--; // a <-- [1,2,3,4,5,6,7,8,9]
// In case you want to shorten your array to 3 elements, you can:
a.length = 3; // a <-- [1,2,3]
When you set the length property of an array to a lower value, the items at the end are removed:
var arr = [1,2,3,4,5];
arr.length; // 5
arr.length = 3;
arr; // [1,2,3]
This is described in the spec:
While newLen < oldLen repeat,
Set oldLen to oldLen – 1.
Let deleteSucceeded be the result of calling the [[Delete]] internal method of A passing ToString(oldLen) and false
as arguments.
In your code you use the postfix decrement operator (--) which reduces the length of the array.