This question already has answers here:
How to remove element from an array in JavaScript?
(12 answers)
Closed 5 years ago.
Trying to delete elements from object using delete , but while the value is gone, there's still "empty" in the object. as show in the image:
which causing unwanted behviour in a following iteration:
for (const [key, value] of ids.entries()) {
if (Object.values(this.widget_ids).indexOf(value) >= 0) {
delete ids[key]
}
}
now, i can't use pop or shift since . i need the option to remove by key, any idea how can i delete and remove this empty slot? or even better, remove while not having do deal with it at all?
You could use Array#splice, which allows to delete at a given index an amount of elements.
delete deletes the element and leaves a sparse array at this index, but it does not changes the lenght of the array.
var ids = [322, 324, 435];
ids.splice(0, 1);
// ^ index
// ^ count of elements to delete
console.log(ids);
Use splice instead of delete, it just set undefined
var ids = [1,2,3];
console.log(ids);
ids.splice(1,1);
console.log(ids);
The problem with delete is that it deletes the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined or empty.
splice(start, deleteCount) removes the element from the array:
var ids = [322, 324, 435];
ids.splice(ids.indexOf(322), ids.indexOf(322) + 1);
console.log(ids);
Related
I have a simple array as
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I need to remove the first index from this array and it should be of below type
[{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I tried splice as below
arr.splice(1,1)
But it is giving response {"name":"ram","value":"2"}
how to get [{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
It might be very simple question but Im stuck here from sometime.can someone plz help
I think you taking the returning value of Array.prototype.splice().
Array.prototype.splice() returns an array containing the deleted elements.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
arr.splice(1,1)
console.log(arr);
You can compare the difference methods. Be aware if you need change the array or just get a copy to keep with the original one.
Attention: The first array index is 0, not 1. The index one is the second element of the array
The splice method return the element removed from array. That's the reason why you've got the second element from array in your test
Doc: https://bytearcher.com/articles/how-to-delete-value-from-array/
In your question you got the second index that is 1, in order to get the values that was shown, I'll use the index 1 as well.
//DELETE
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
delete arr[1];
console.log("using delete",arr)
//SPLICE METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let firstElement = arr.splice(1,1)
console.log("using splice",arr)
console.log("the method splice return the element removed from array",firstElement )
//FILTER METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let copyArr = arr.filter((element, index)=>index !== 1)
console.log("extra: using filter (will return a array copy)",copyArr)
This question already has answers here:
Filter and delete filtered elements in an array
(10 answers)
Closed 3 years ago.
I am iterating over an array of strings using forEach(), and testing each element's length to determine wether it is even or odd. If the length of the string is even, it will be removed using splice().
My input and output are shown below, and as you can see even though (i think) my conditions are correct, in my return array, I still get an even, two character word - which should have been spliced out.
Code:
function filterOddLengthWords(words) {
words.forEach(function(element, index) {
if (element.length%2===0) {
words.splice(index, 1);
}
})
return words;
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output); // --> [ 'there', 'is', 'now' ]
I understand where the error is, but I just don't know how to compensate for it. I could possibly rewrite this by creating an empty array at the beginning of the function, and then testing each element against the inverse condition, using the push() method to add each positive to the empty array. However, that is more inefficient and I'm curious to see if my way is possible. Thanks for the answers in advance.
By splicing an array, you change the index, but forEach takes the elements in advance and the old indices.
Usually by using splice, the iteration is started from the end and if some item is remoce, the index remains for the items before.
You could filter the array.
function filterOddLengthWords(words) {
return words.filter(function(element) {
return element.length % 2;
});
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output);
The problem with splicing the array in the forEach() is that when you splice() on the array at index 1 which has the element it the element at index 2 is is moved to index 1.
So in the next iteration when the index is 2 in the callback the element at the index 2 of the array is the value now instead of the element is. As now is odd it is kept but the element is is completely skipped.
Using Array.prototype.filter will work here as it does not modify the original array but instead collects the valid results into a new array.
This question already has answers here:
Deleting array elements in JavaScript - delete vs splice
(29 answers)
Closed 4 years ago.
I couldn't find a question that specifically targets the issue I'm having hence this question is being asked.
I have an array that holds 5 numbers:
var numbers = [0,1,2,3,4];
Once a number is clicked on the frontend (website), the number is removed from the array using the below code:
delete numbers[1];
This removes the correct number but leaves a space where the number was (the space is undefined). I believe this is causing an issue. After a number is removed from the array, I use another function to randomly pick any of the remaining numbers in the array however it sometimes fails. After much thought, I've realized it may be because there are empty spaces in the array after a number is removed and as a result, the code fails to work due to the undefined element.
Is my analogy correct or am I mistaken?
(I have also attempted to use the splice method to remove the number however that then causes an issue with the length of my array because if I later want to remove another number, it removes the wrong one due to the numbers moving around etc).
What you'd want to use is splice
In your specific case, numbers.splice(1,1)
You're correct that delete replaces one of the values in the array with undefined, and does not change the array length. Later on when you randomly choose an element from the array, you can wind up getting that undefined value, because it's still taking up a slot in the array:
var numbers = [0,1,2,3,4];
delete numbers[3];
console.log(numbers)
Instead use splice, which removes the item from the array completely:
var numbers = [0,1,2,3,4];
numbers.splice(3,1) /// remove one element starting at index 3
console.log(numbers)
if I later want to remove another number, it removes the wrong one due to the numbers moving around
You do need to choose one behavior or the other. If you need to preserve indexes as is, then continue to use delete, leaving the undefined values in the array, and rewrite your "choose one at random" function to never pick undefined values:
// start with some undefined values:
var numbers = [0, 1, undefined, undefined, undefined, 5]
var pickRandom = function(numbers) {
// make a copy of the array, removing undefined elements:
var definedValues = numbers.filter(function(item) {
return item !== undefined;
});
if (definedValues.length === 0) {return false}
//choose one at random:
return definedValues[Math.floor(Math.random() * definedValues.length)]
}
// test it:
console.log(pickRandom(numbers));
console.log(pickRandom(numbers));
console.log(pickRandom(numbers));
console.log(pickRandom(numbers));
(...but note that this suggests that a simple array is the wrong data structure to use here; you may be better off with an array of objects each with an explicit ID, so you can reference specific ones as needed without worrying about keeping the array index the same.)
If you mean to actually remove the element from the array, leaving your array with 4 elements, then you can use
numbers.splice(1);
This will remove the element in the index 1 from the array and return the section of the new array.
This question already has answers here:
Get the last item in an array
(59 answers)
Closed 5 years ago.
I am new to node.js and JavaScript so this question might be quite simple but I cannot figure it out.
I have a lot of items in an array but only want to get the last item. I tried to use lodash but it somehow does not provide me with the last item in the array.
My array looks like this now:
images : ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', ..., 'jpg.item_n']
and i want to get:
images : 'jpg.item_n'
Using lodash I am getting:
images : ['g.item_1', 'g.item_2', 'g.item_n']
It looks like I am just getting the last letter in jpg, i.e. 'g'.
My code using lodash looks like this:
const _ = require('lodash');
return getEvents().then(rawEvents => {
const eventsToBeInserted = rawEvents.map(event => {
return {
images: !!event.images ? event.images.map(image => _.last(image.url)) : []
}
})
})
Your problem is that you're using _.last inside map. This will get the last character in the current item. You want to get the last element of the actual Array.
You can do this with pop(), however it should be noted that it is destructive (will remove the last item from the array).
Non-destructive vanilla solution:
var arr = ['thing1', 'thing2'];
console.log(arr[arr.length-1]); // 'thing2'
Or, with lodash:
_.last(event.images);
Use .pop() array method
var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
var index= images.length - 1; //Last index of array
console.log(images[index]);
//or,
console.log(images.pop())// it will remove the last item from array
Although Array.prototype.pop retrieves the last element of the array it also removes this element from the array. So one should combine Array.prototype.pop with Array.prototype.slice:
var images = ['jpg.item_1', 'jpg.item_2', 'jpg.item_3', 'jpg.item_n'];
console.log(images.slice(-1).pop());
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 8 years ago.
Using an angular array how do I add and remove elements between the two arrays?
I have $scope.results and $scope.list the results array is the result of a call to a WebAPI and i'm allowing the user to select the elements they want to add to the second array. How do i add from the first to the second and remove from the first at the same time?
angular.forEach($scope.results, function (item) {
if (item.selected) {
$scope.list.push(item);
//CODE TO REMOVE item from $scope.results here.
};
});
Additionally if i did a second search and tried to add the same member from the first array to my second array (which already had this user) how do i prevent adding duplicates to the second array (list)?.
below is a sample of the objects im wanted to transfer between the arrays. the id field is the indicator of uniqueness.
You can get index as second parameter of angular.forEach. Then us splice to remove the item from original array. Check the code below.
angular.forEach($scope.results, function (item, index) {
if (item.selected) {
$scope.list.push(item);
$scope.results.splice(index, 1);
};
});
I just realized there is a drawback in using splice inside angular.forEach loop that it will reindex the array after removing the item. So the immediate next item will be skipped if an item is removed.
So below would be the right solution.
var len = $scope.results.length;
while (len--) {
var item = $scope.results[len];
if (item.selected) {
$scope.list.push(item);
$scope.results.splice(len, 1);
};
}
Thanks.