How expensive are push() and pop() array methods? Do they create a whole new array?
Array.pop - last two elements - JavaScript - Stack Overflow
How can I remove an array element at a specific index only using pop?
When calling this .pop method to an array, why am I getting an unexpected .length result
Videos
If I create an empty array to use as a stack and use push() and pop() methods on it, is javascript creating a whole new array behind the scenes (which is expensive) or is it simply allocating memory for the new spot for that single element in case of a push and reclaiming it for pop?
Split the array, use Array#slice to get the last two elements, and then Array#join with slashes:
var url = 'www.example.com/products/cream/handcreamproduct1';
var lastTWo = url
.split("/") // split to an array
.slice(-2) // take the two last elements
.join('/') // join back to a string;
console.log(lastTWo);
I love the new array methods like filter so there is a demo with using this
let o = 'www.example.com/products/cream/handcreamproduct1'.split('/').filter(function(elm, i, arr){
if(i>arr.length-3){
return elm;
}
});
console.log(o);
You should only add to the result array in the if condition, not else. Use j as the index in the result, don't add or subtract it.
function removeAt(arr, index) {
var j = 0;
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
if (i != index) {
arr2[j] = arr[i];
j++;
}
}
return arr2
}
console.log(removeAt([1, 2, 3, 4, 5], 3))
If you are not allowed to use any Array function except pop(), you may save memory space by not creating an extra variable using it.
function removeAt(arr, index){
if(index>arr.length-1 || index<0) return arr;
for(let i=0; i<arr.length; i++) {
if(i>=index) {
arr[i] = arr[i+1];
}
}
arr.pop();
return arr;
}
The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.
var arr = [1, 2, 3, 4];
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
Just use arr.slice(startingIndex, endingIndex).
If you do not specify the endingIndex, it returns all the items starting from the index provided.
In your case arr=arr.slice(1).