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());
Related
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:
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);
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.
This question already has answers here:
Javascript swap array elements
(33 answers)
Closed 9 years ago.
I have an array of objects and I want to swap the position of two elements in the array.
I tried this:
var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);
But it doesn't seem to work properly as it results in some weird errors. For example, I am unable to use methods of the object. Calling array[x].getName results in an error.
Can any body lend a helping hand here?
Just in case it is important, I have used object.prototype to add the methods.
The bug in your code is that splice returns an array of items, not a single item. Since you are extracting a single item, you could do:
var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);
This answer provides a shorter version, also using splice:
array[index] = array.splice(index+1, 1, array[index])[0];
Another very interesting answer is both short and fast:
function identity(x){return x};
array[index] = identity(array[index+1], array[index+1]=array[index]);
JSFIDDLE
var array_of_numbers = [5,4,3,2,1,0],
swap = function(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;};
swap(array_of_numbers,0,4);
// array_of_numbers now is [1,4,3,2,5,0]
Or you can do add the function to the Array.prototype:
JSFIDDLE
Array.prototype.swap = function(a,b){ var tmp=this[a];this[a]=this[b];this[b]=tmp;};
var array_of_numbers = [5,4,3,2,1,0];
array_of_numbers.swap(0,4);
// array_of_numbers now is [1,4,3,2,5,0]
This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 9 years ago.
I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.
I did this with the following:
var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
QUESTION:
I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?
Here's a oneliner:
var myArr = Array(20).join().split(',').map(function(a){return this.i++},{i:1});
or a tiny bit shorter:
var myArr = (''+Array(20)).split(',').map(function(){return this[0]++;}, [1]);
Both methods create an empty Array with 20 empty elements (i.e. elements with value undefined). On a thus created Array the map method can't be applied 1, so the join (or string addition) and split trick transforms it to an Array that knows it. Now the map callback (see the MDN link) does nothing more than sending an increment of the initial value ({i:1} or [1]) back for each element of the Array, and after that, myArr contains 20 numeric values from 1 to 20.
Addendum: ES20xx
[...Array(21).keys()].slice(1);
Array.map => See also...
See also this Stackblitz project.
1 Why not? See this SO answer, and this one for a more profound explanation
You could use a simple loop to do what you want;
var numberArray = [];
for(var i = 1; i <= 20; i++){
numberArray.push(i);
}
console.log(numberArray);