Can I limit the length of an array in JavaScript? - javascript

I want to display the product browsing history, so I am storing the product ids in a browser cookie.
Because the list of history is limited to 5 items, I convert the cookie value to an array, then check the length of it and cut the redundant.
The code below is what I have tried, but it does not work; the array item isn't removed.
I would like to ask how to limit the array length so it can only store 5 items?
Or
How can I cut the items after the array index 4?
var id = product_id;
var browseHistory = $.cookie('history');
if (browseHistory != null) {
var old_cookie = $.cookie('history');
var new_cookie = '';
if (old_cookie.indexOf(',') != -1) {
var arr = old_cookie.split(',');
if (arr.length >= 5) {
arr.splice(4, 1)
}
}
new_cookie = id + ',' + old_cookie;
$.cookie('history', new_cookie, { expires: 7, path: '/' });
} else {
$.cookie('history', id, { expires: 7, path: '/' });
}

You're not using splice correctly:
arr.splice(4, 1)
this will remove 1 item at index 4. see here
I think you want to use slice:
arr.slice(0,5)
this will return elements in position 0 through 4.
This assumes all the rest of your code (cookies etc) works correctly

The fastest and simplest way is by setting the .length property to the desired length:
arr.length = 4;
This is also the desired way to reset/empty arrays:
arr.length = 0;
Caveat: setting this property can also make the array longer than it is: If its length is 2, running arr.length = 4 will add two undefined items to it. Perhaps add a condition:
if (arr.length > 4) arr.length = 4;
Alternatively:
arr.length = Math.min(arr.length, 4);

arr.length = Math.min(arr.length, 5)

var arrLength = arr.length;
if(arrLength > maxNumber){
arr.splice( 0, arrLength - maxNumber);
}
This solution works better in a dynamic environment like p5js. I put this inside the draw call and it clamps the length of the array dynamically.
The problem with
arr.slice(0,5)
is that it only takes a fixed number of items off the array per draw frame, which won't be able to keep the array size constant if your user can add multiple items.
The problem with
if (arr.length > 4) arr.length = 4;
is that it takes items off the end of the array, so which won't cycle through the array if you are also adding to the end with push().

I think you could just do:
let array = [];
array.length = 2;
Object.defineProperty(array, 'length', {writable:false});
array[0] = 1 // [1, undefined]
array[1] = 2 // [1, 2]
array[2] = 3 // [1, 2] -> doesn't add anything and fails silently
array.push("something"); //but this throws an Uncaught TypeError

I was surprised nobody mentioned the following snippet to limit the length of the array:
arr.splice(5);
According to the Parameters definitions for splice, if start is larger than the length of the array, it will be set to the length of the array, and if deleteCount is omitted or larger than the array length, all of the items after start will be deleted.
Therefore, if you want to limit an array to some MAX_SIZE (modifying the existing array instead of creating a new instance) an easy shortcut is just arr.splice(MAX_SIZE).
As others have said, there is more going on with the code in the question, but given the title and spirit of the ask, I hope this is a useful answer for anyone else ending up here via search.
Note: According to the compatibility notes for IE 5.5-8, deleteCount does not work as described above, so this solution won't work right on those browsers.

You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.
You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).
You should convert the shortened array back to a string with .join(",") and then use it for the new cookie instead of using old_cookie which is not shortened.
You may also not be using .splice() correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice() here.

Came here but couldn't find a functional way of limiting the length of an array.
So I came up with:
const list = ["a","b","c","d","e","f","g","h","i"];
const listWithOnly3Items = list.filter((element,index) => index < 3);

Related

jQuery DataTable not working filter with negative index [duplicate]

Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
if (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
EDIT - ES-2022
Using ES-2022 Array.at(), the above may be written like this:
if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined if the array is empty.
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
A shorter version of what #chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
Performance
Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6
Conclusions
arr[arr.length-1] (D) is recommended as fastest cross-browser solution
mutable solution arr.pop() (A) and immutable _.last(arr) (L) are fast
solutions I, J are slow for long strings
solutions H, K (jQuery) are slowest on all browsers
Details
I test two cases for solutions:
mutable: A,
B,
C,
immutable: D,
E,
F,
G,
H,
I,
J (my),
immutable from external libraries: K,
L,
M,
for two cases
short string - 10 characters - you can run test HERE
long string - 1M characters - you can run test HERE
function A(arr) {
return arr.pop();
}
function B(arr) {
return arr.splice(-1,1);
}
function C(arr) {
return arr.reverse()[0]
}
function D(arr) {
return arr[arr.length - 1];
}
function E(arr) {
return arr.slice(-1)[0] ;
}
function F(arr) {
let [last] = arr.slice(-1);
return last;
}
function G(arr) {
return arr.slice(-1).pop();
}
function H(arr) {
return [...arr].pop();
}
function I(arr) {
return arr.reduceRight(a => a);
}
function J(arr) {
return arr.find((e,i,a)=> a.length==i+1);
}
function K(arr) {
return $(arr).get(-1);
}
function L(arr) {
return _.last(arr);
}
function M(arr) {
return _.nth(arr, -1);
}
// ----------
// TEST
// ----------
let loc_array=["domain","a","b","c","d","e","f","g","h","file"];
log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);
[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
Example results for Chrome for short string
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
Getting the last item is possible via the length property. Since the array count starts at 0, you can pick the last item by referencing the array.length - 1 item
const arr = [1,2,3,4];
const last = arr[arr.length - 1];
console.log(last); // 4
Another option is using the new Array.prototype.at() method which takes an integer value and returns the item at that index. Negative integers count back from the last item in the array so if we want the last item we can just pass in -1
const arr = [1,2,3,4];
const last = arr.at(-1);
console.log(last); // 4
Another option is using the new findLast method. You can see the proposal here
const arr = [1,2,3,4];
const last = arr.findLast(x => true);
console.log(last); // 4
Another option is using the Array.prototype.slice() method which returns a shallow copy of a portion of an array into a new array object.
const arr = [1,2,3,4];
const last = arr.slice(-1)[0];
console.log(last); // 4
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo, as .pop() would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0] solution.
const [lastItem] = array.slice(-1);
Array.prototype.slice with -1 can be used to create a new Array containing only the last item of the original Array, you can then use Destructuring Assignment to create a variable using the first item of that new Array.
const lotteryNumbers = [12, 16, 4, 33, 41, 22];
const [lastNumber] = lotteryNumbers.slice(-1);
console.log(lotteryNumbers.slice(-1));
// => [22]
console.log(lastNumber);
// => 22
const [y] = x.slice(-1)
Quick Explanation:
This syntax [y] = <array/object> is called destructuring assignment & according to Mozilla docs, the destructuring assingment makes possible to unpack values from an array or properties from an object into distinct variables
Read more about it: here
I'd rather use array.pop() than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
You can use relative indexing with Array#at:
const myArray = [1, 2, 3]
console.log(myArray.at(-1))
// => 3
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
If one wants to get the last element in one go, he/she may use Array#splice():
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1) as a pop() function that pops the last element.
Multiple ways to find last value of an array in javascript
Without affecting original array
var arr = [1,2,3,4,5];
console.log(arr.slice(-1)[0])
console.log(arr[arr.length-1])
const [last] = [...arr].reverse();
console.log(last)
let copyArr = [...arr];
console.log(copyArr.reverse()[0]);
Modifies original array
var arr = [1,2,3,4,5];
console.log(arr.pop())
arr.push(5)
console.log(...arr.splice(-1));
By creating own helper method
let arr = [1, 2, 3, 4, 5];
Object.defineProperty(arr, 'last',
{ get: function(){
return this[this.length-1];
}
})
console.log(arr.last);
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop().
arr.pop() is exactly as efficient as arr[arr.length-1], and both are the same speed as arr.push().
Therefore, you can get away with:
---EDITED [check that thePop isn't undefined before pushing]---
let thePop = arr.pop()
thePop && arr.push(thePop)
---END EDIT---
Which can be reduced to this (same speed [EDIT: but unsafe!]):
arr.push(thePop = arr.pop()) //Unsafe if arr empty
This is twice as slow as arr[arr.length-1], but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop(), get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop() probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
Just putting another option here.
loc_array.splice(-1)[0] === 'index.html'
I found the above approach more clean and short onliner. Please, free feel to try this one.
Note: It will modify the original array, if you don't want to modify it you can use slice()
loc_array.slice(-1)[0] === 'index.html'
Thanks #VinayPai for pointing this out.
Here's more Javascript art if you came here looking for it
In the spirit of another answer that used reduceRight(), but shorter:
[3, 2, 1, 5].reduceRight(a => a);
It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.
Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.
And now for the serious answer
The best way I see (considering you want it more concise than array[array.length - 1]) is this:
const last = a => a[a.length - 1];
Then just use the function:
last([3, 2, 1, 5])
The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5] used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:
[3, 2, 1, 5][[3, 2, 1, 5].length - 1]
Ugh.
For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last() instead:
last("1.2.3".split("."));
ES6 object destructuring is another way to go.
const {length, [length-1]: last}=[1,2,3,4,5]
console.log(last)
You extract length property from Array using object destructuring. You create another dynamic key using already extracted key by [length-1] and assign it to last, all in one line.
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined
To prevent removing last item from origin array you could use
Array.from(myArray).pop()
Mostly supported of all browsers (ES6)
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
I think this should work fine.
var arr = [1, 2, 3];
var last_element = arr.reverse()[0];
Just reverse the array and get the first element.
Edit: As mentioned below, the original array will be reversed. To avoid that you can change the code to:
var arr = [1, 2, 3];
var last_element = arr.slice().reverse()[0];
This will create a copy of the original array.
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
​
array.slice(-1)[0]
​
//instead of
​
array[array.length-1]
​
//Much easier to read with nested arrays
​
array.slice(-1)[0].slice(-1)[0]
​
//instead of
​
array[array.length-1][array[array.length-1].length-1]
Whatever you do don't just use reverse() !!!
A few answers mention reverse but don't mention the fact that reverse modifies the original array, and doesn't (as in some other language or frameworks) return a copy.
var animals = ['dog', 'cat'];
animals.reverse()[0]
"cat"
animals.reverse()[0]
"dog"
animals.reverse()[1]
"dog"
animals.reverse()[1]
"cat"
This can be the worst type of code to debug!

javaScript: how do i check if argument matches the last string in an array [duplicate]

Here is my JavaScript code so far:
var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
linkElement.appendChild(newT);
Currently it takes the second to last item in the array from the URL. However, I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.
if (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
EDIT - ES-2022
Using ES-2022 Array.at(), the above may be written like this:
if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}
Not sure if there's a drawback, but this seems quite concise:
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined if the array is empty.
Use Array.pop:
var lastItem = anArray.pop();
Important : This returns the last element and removes it from the array
A shorter version of what #chaiguy posted:
Array.prototype.last = function() {
return this[this.length - 1];
}
Reading the -1 index returns undefined already.
EDIT:
These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.
export function last(array) {
return array[array.length - 1];
}
Two options are:
var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
Performance
Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6
Conclusions
arr[arr.length-1] (D) is recommended as fastest cross-browser solution
mutable solution arr.pop() (A) and immutable _.last(arr) (L) are fast
solutions I, J are slow for long strings
solutions H, K (jQuery) are slowest on all browsers
Details
I test two cases for solutions:
mutable: A,
B,
C,
immutable: D,
E,
F,
G,
H,
I,
J (my),
immutable from external libraries: K,
L,
M,
for two cases
short string - 10 characters - you can run test HERE
long string - 1M characters - you can run test HERE
function A(arr) {
return arr.pop();
}
function B(arr) {
return arr.splice(-1,1);
}
function C(arr) {
return arr.reverse()[0]
}
function D(arr) {
return arr[arr.length - 1];
}
function E(arr) {
return arr.slice(-1)[0] ;
}
function F(arr) {
let [last] = arr.slice(-1);
return last;
}
function G(arr) {
return arr.slice(-1).pop();
}
function H(arr) {
return [...arr].pop();
}
function I(arr) {
return arr.reduceRight(a => a);
}
function J(arr) {
return arr.find((e,i,a)=> a.length==i+1);
}
function K(arr) {
return $(arr).get(-1);
}
function L(arr) {
return _.last(arr);
}
function M(arr) {
return _.nth(arr, -1);
}
// ----------
// TEST
// ----------
let loc_array=["domain","a","b","c","d","e","f","g","h","file"];
log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);
[A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
Example results for Chrome for short string
Here's how to get it with no effect on the original ARRAY
a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements
If you use pop(), it will modify your array
a.pop(); // will return "abc" AND REMOVES IT from the array
a.length; // returns 7
But you can use this so it has no effect on the original array:
a.slice(-1).pop(); // will return "abc" won't do modify the array
// because slice creates a new array object
a.length; // returns 8; no modification and you've got you last element
Getting the last item is possible via the length property. Since the array count starts at 0, you can pick the last item by referencing the array.length - 1 item
const arr = [1,2,3,4];
const last = arr[arr.length - 1];
console.log(last); // 4
Another option is using the new Array.prototype.at() method which takes an integer value and returns the item at that index. Negative integers count back from the last item in the array so if we want the last item we can just pass in -1
const arr = [1,2,3,4];
const last = arr.at(-1);
console.log(last); // 4
Another option is using the new findLast method. You can see the proposal here
const arr = [1,2,3,4];
const last = arr.findLast(x => true);
console.log(last); // 4
Another option is using the Array.prototype.slice() method which returns a shallow copy of a portion of an array into a new array object.
const arr = [1,2,3,4];
const last = arr.slice(-1)[0];
console.log(last); // 4
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo, as .pop() would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0] solution.
const [lastItem] = array.slice(-1);
Array.prototype.slice with -1 can be used to create a new Array containing only the last item of the original Array, you can then use Destructuring Assignment to create a variable using the first item of that new Array.
const lotteryNumbers = [12, 16, 4, 33, 41, 22];
const [lastNumber] = lotteryNumbers.slice(-1);
console.log(lotteryNumbers.slice(-1));
// => [22]
console.log(lastNumber);
// => 22
const [y] = x.slice(-1)
Quick Explanation:
This syntax [y] = <array/object> is called destructuring assignment & according to Mozilla docs, the destructuring assingment makes possible to unpack values from an array or properties from an object into distinct variables
Read more about it: here
I'd rather use array.pop() than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
You can use relative indexing with Array#at:
const myArray = [1, 2, 3]
console.log(myArray.at(-1))
// => 3
const lastElement = myArray[myArray.length - 1];
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
You can use this pattern...
let [last] = arr.slice(-1);
While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.
If one wants to get the last element in one go, he/she may use Array#splice():
lastElement = document.location.href.split('/').splice(-1,1);
Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of splice(-1,1) as a pop() function that pops the last element.
Multiple ways to find last value of an array in javascript
Without affecting original array
var arr = [1,2,3,4,5];
console.log(arr.slice(-1)[0])
console.log(arr[arr.length-1])
const [last] = [...arr].reverse();
console.log(last)
let copyArr = [...arr];
console.log(copyArr.reverse()[0]);
Modifies original array
var arr = [1,2,3,4,5];
console.log(arr.pop())
arr.push(5)
console.log(...arr.splice(-1));
By creating own helper method
let arr = [1, 2, 3, 4, 5];
Object.defineProperty(arr, 'last',
{ get: function(){
return this[this.length-1];
}
})
console.log(arr.last);
Getting the last item of an array can be achieved by using the slice method with negative values.
You can read more about it here at the bottom.
var fileName = loc_array.slice(-1)[0];
if(fileName.toLowerCase() == "index.html")
{
//your code...
}
Using pop() will change your array, which is not always a good idea.
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop().
arr.pop() is exactly as efficient as arr[arr.length-1], and both are the same speed as arr.push().
Therefore, you can get away with:
---EDITED [check that thePop isn't undefined before pushing]---
let thePop = arr.pop()
thePop && arr.push(thePop)
---END EDIT---
Which can be reduced to this (same speed [EDIT: but unsafe!]):
arr.push(thePop = arr.pop()) //Unsafe if arr empty
This is twice as slow as arr[arr.length-1], but you don't have to stuff around with an index. That's worth gold on any day.
Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]:
[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
arr[arr.length - 1] ------> 1 -----> 1
let myPop = arr.pop()
arr.push(myPop) ------> 2 -----> 2
arr.slice(-1).pop() ------> 36 -----> 924
arr.slice(-1)[0] ------> 36 -----> 924
[...arr].pop() ------> 120 -----> ~21,000,000 :)
The last three options, ESPECIALLY [...arr].pop(), get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop() probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.
Just putting another option here.
loc_array.splice(-1)[0] === 'index.html'
I found the above approach more clean and short onliner. Please, free feel to try this one.
Note: It will modify the original array, if you don't want to modify it you can use slice()
loc_array.slice(-1)[0] === 'index.html'
Thanks #VinayPai for pointing this out.
Here's more Javascript art if you came here looking for it
In the spirit of another answer that used reduceRight(), but shorter:
[3, 2, 1, 5].reduceRight(a => a);
It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.
Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.
And now for the serious answer
The best way I see (considering you want it more concise than array[array.length - 1]) is this:
const last = a => a[a.length - 1];
Then just use the function:
last([3, 2, 1, 5])
The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5] used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:
[3, 2, 1, 5][[3, 2, 1, 5].length - 1]
Ugh.
For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last() instead:
last("1.2.3".split("."));
ES6 object destructuring is another way to go.
const {length, [length-1]: last}=[1,2,3,4,5]
console.log(last)
You extract length property from Array using object destructuring. You create another dynamic key using already extracted key by [length-1] and assign it to last, all in one line.
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
Object.defineProperty( Array.prototype, "getLast", {
enumerable: false,
configurable: false,
writable: false,
value: function() {
return this[ this.length - 1 ];
}
} );
I generally use underscorejs, with it you can just do
if (_.last(loc_array) === 'index.html'){
etc...
}
For me that is more semantic than loc_array.slice(-1)[0]
jQuery solves this neatly:
> $([1,2,3]).get(-1)
3
> $([]).get(-1)
undefined
To prevent removing last item from origin array you could use
Array.from(myArray).pop()
Mostly supported of all browsers (ES6)
In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.
Syntax:
arr.lastItem // get last item
arr.lastItem = 'value' // set last item
arr.lastIndex // get last index
You can use polyfill.
Proposal author: Keith Cirkel(chai autor)
I think this should work fine.
var arr = [1, 2, 3];
var last_element = arr.reverse()[0];
Just reverse the array and get the first element.
Edit: As mentioned below, the original array will be reversed. To avoid that you can change the code to:
var arr = [1, 2, 3];
var last_element = arr.slice().reverse()[0];
This will create a copy of the original array.
Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.
var array = [[1,2,3], [4,5,6], [7,8,9]]
​
array.slice(-1)[0]
​
//instead of
​
array[array.length-1]
​
//Much easier to read with nested arrays
​
array.slice(-1)[0].slice(-1)[0]
​
//instead of
​
array[array.length-1][array[array.length-1].length-1]
Whatever you do don't just use reverse() !!!
A few answers mention reverse but don't mention the fact that reverse modifies the original array, and doesn't (as in some other language or frameworks) return a copy.
var animals = ['dog', 'cat'];
animals.reverse()[0]
"cat"
animals.reverse()[0]
"dog"
animals.reverse()[1]
"dog"
animals.reverse()[1]
"cat"
This can be the worst type of code to debug!

How do I remove all the elements of an array using splice [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is there a way to empty an array and if so possibly with .remove()?
For instance,
A = [1,2,3,4];
How can I empty that?
Ways to clear an existing array A:
Method 1
(this was my original answer to the question)
A = [];
This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.
This is also the fastest solution.
This code sample shows the issue you can encounter when using this method:
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
Method 2 (as suggested by Matthew Crumley)
A.length = 0
This will clear the existing array by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.
Method 3 (as suggested by Anthony)
A.splice(0,A.length)
Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.
Method 4 (as suggested by tanguy_k)
while(A.length > 0) {
A.pop();
}
This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.
Performance
Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.
As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.
The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).
This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:
A.length = 0;
Here the fastest working implementation while keeping the same array ("mutable"):
function clearArray(array) {
while (array.length > 0) {
array.pop();
}
}
FYI it cannot be simplified to while (array.pop()): the tests will fail.
FYI Map and Set define clear(), it would have seem logical to have clear() for Array too.
TypeScript version:
function clearArray<T>(array: T[]) {
while (array.length > 0) {
array.pop();
}
}
The corresponding tests:
describe('clearArray()', () => {
test('clear regular array', () => {
const array = [1, 2, 3, 4, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
test('clear array that contains undefined and null', () => {
const array = [1, undefined, 3, null, 5];
clearArray(array);
expect(array.length).toEqual(0);
expect(array[0]).toEqual(undefined);
expect(array[4]).toEqual(undefined);
});
});
Here the updated jsPerf: http://jsperf.com/array-destroy/32 http://jsperf.com/array-destroy/152
jsPerf offline. Similar benchmark: https://jsben.ch/hyj65
A more cross-browser friendly and more optimal solution will be to use the splice method to empty the content of the array A as below:
A.splice(0, A.length);
The answers that have no less that 2739 upvotes by now are misleading and incorrect.
The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4].
Saying "A = [] is the answer" is ignorant and absolutely incorrect. [] == [] is false.
This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.
Let's say your mother asks you to empty the trash can.
You don't bring in a new one as if you've done what you've been asked for.
Instead, you empty the trash can.
You don't replace the filled one with a new empty can, and you don't take the label "A" from the filled can and stick it to the new one as in A = [1,2,3,4]; A = [];
Emptying an array object is the easiest thing ever:
A.length = 0;
This way, the can under "A" is not only empty, but also as clean as new!
Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:
while(A.length > 0) {
A.pop();
}
Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:
A.splice(0, A.length);
No, you were asked to empty it:
A.length = 0;
This is the only code that correctly empties the contents of a given JavaScript array.
Performance test:
http://jsperf.com/array-clear-methods/3
a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length) // 97% slower
while (a.length > 0) {
a.pop();
} // Fastest
You can add this to your JavaScript file to allow your arrays to be "cleared":
Array.prototype.clear = function() {
this.splice(0, this.length);
};
Then you can use it like this:
var list = [1, 2, 3];
list.clear();
Or if you want to be sure you don't destroy something:
if (!Array.prototype.clear) {
Array.prototype.clear = function() {
this.splice(0, this.length);
};
}
Lots of people think you shouldn't modify native objects (like Array), and I'm inclined to agree. Please use caution in deciding how to handle this.
You can easily create a function to do that for you, change the length or even add it to native Array as remove() function for reuse.
Imagine you have this array:
var arr = [1, 2, 3, 4, 5]; //the array
OK, just simply run this:
arr.length = 0; //change the length
and the result is:
[] //result
easy way to empty an array...
Also using loop which is not necessary but just another way to do that:
/* could be arr.pop() or arr.splice(0)
don't need to return as main array get changed */
function remove(arr) {
while(arr.length) {
arr.shift();
}
}
There are also tricky way which you can think about, for example something like this:
arr.splice(0, arr.length); //[]
So if arr has 5 items, it will splice 5 items from 0, which means nothing will remain in the array.
Also other ways like simply reassign the array for example:
arr = []; //[]
If you look at the Array functions, there are many other ways to do this, but the most recommended one could be changing the length.
As I said in the first place, you can also prototype remove() as it's the answer to your question. you can simply choose one of the methods above and prototype it to Array object in JavaScript, something like:
Array.prototype.remove = Array.prototype.remove || function() {
this.splice(0, this.length);
};
and you can simply call it like this to empty any array in your javascript application:
arr.remove(); //[]
If you are using
a = [];
Then you are assigning new array reference to a, if reference in a is already assigned to any other variable, then it will not empty that array too and hence garbage collector will not collect that memory.
For ex.
var a=[1,2,3];
var b=a;
a=[];
console.log(b);// It will print [1,2,3];
or
a.length = 0;
When we specify a.length, we are just resetting boundaries of the array and memory for rest array elements will be connected by garbage collector.
Instead of these two solutions are better.
a.splice(0,a.length)
and
while(a.length > 0) {
a.pop();
}
As per previous answer by kenshou.html, second method is faster.
There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg:
var arr = [];
for (var i = 0; i < 100; i++) {
arr.push(Math.random());
}
for (var j = 0; j < 1000; j++) {
while (arr.length > 0) {
arr.pop(); // this executes 100 times, not 100000
}
}
I have created a new test that works correctly :
http://jsperf.com/empty-javascript-array-redux
Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).
Array.prototype.clear = function() {
this.length = 0;
};
And call it: array.clear();
In case you are interested in the memory allocation, you may compare each approach using something like this jsfiddle in conjunction with chrome dev tools' timeline tab. You will want to use the trash bin icon at the bottom to force a garbage collection after 'clearing' the array. This should give you a more definite answer for the browser of your choice. A lot of answers here are old and I wouldn't rely on them but rather test as in #tanguy_k's answer above.
(for an intro to the aforementioned tab you can check out here)
Stackoverflow forces me to copy the jsfiddle so here it is:
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]="something"
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
And you should take note that it may depend on the type of the array elements, as javascript manages strings differently than other primitive types, not to mention arrays of objects. The type may affect what happens.
Use a modified version of Jan's initial suggestion:
var originalLength = A.length;
for (var i = originalLength; i > 0; i--) {
A.pop();
}
Terser:
for (let i = A.length; i > 0;A.pop(),i--) {}
Or here's another take:
while(!A[Symbol.iterator]().next().done)A.shift()
A.splice(0);
I just did this on some code I am working on. It cleared the array.
If you use constants then you have no choice:
const numbers = [1, 2, 3]
You can not reasign:
numbers = []
You can only truncate:
numbers.length = 0
To Empty a Current memory location of an array use: 'myArray.length = 0' or 'myArray.pop() UN-till its length is 0'
length : You can set the length property to truncate an array at any time. When you extend an array by changing its length property, the number of actual elements increases.
pop() : The pop method removes the last element from an array and returns that returns the removed value.
shift() : The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.
Example:
var arr = ['77'];
arr.length = 20;
console.log("Increasing : ", arr); // (20) ["77", empty × 19]
arr.length = 12;
console.log("Truncating : ", arr); // (12) ["77", empty × 11]
var mainArr = new Array();
mainArr = ['1', '2', '3', '4'];
var refArr = mainArr;
console.log('Current', mainArr, 'Refered', refArr);
refArr.length = 3;
console.log('Length: ~ Current', mainArr, 'Refered', refArr);
mainArr.push('0');
console.log('Push to the End of Current Array Memory Location \n~ Current', mainArr, 'Refered', refArr);
mainArr.poptill_length(0);
console.log('Empty Array \n~ Current', mainArr, 'Refered', refArr);
Array.prototype.poptill_length = function (e) {
while (this.length) {
if( this.length == e ) break;
console.log('removed last element:', this.pop());
}
};
new Array() | [] Create an Array with new memory location by using Array constructor or array literal.
mainArr = []; // a new empty array is addressed to mainArr.
var arr = new Array('10'); // Array constructor
arr.unshift('1'); // add to the front
arr.push('15'); // add to the end
console.log("After Adding : ", arr); // ["1", "10", "15"]
arr.pop(); // remove from the end
arr.shift(); // remove from the front
console.log("After Removing : ", arr); // ["10"]
var arrLit = ['14', '17'];
console.log("array literal « ", indexedItem( arrLit ) ); // {0,14}{1,17}
function indexedItem( arr ) {
var indexedStr = "";
arr.forEach(function(item, index, array) {
indexedStr += "{"+index+","+item+"}";
console.log(item, index);
});
return indexedStr;
}
slice() : By using slice function we get an shallow copy of elements from the original array, with new memory address, So that any modification on cloneArr will not affect to an actual|original array.
var shallowCopy = mainArr.slice(); // this is how to make a copy
var cloneArr = mainArr.slice(0, 3);
console.log('Main', mainArr, '\tCloned', cloneArr);
cloneArr.length = 0; // Clears current memory location of an array.
console.log('Main', mainArr, '\tCloned', cloneArr);
I'm surprised no one has suggested this yet:
let xs = [1,2,3,4];
for (let i in xs)
delete xs[i];
This yields an array in quite a different state from the other solutions. In a sense, the array has been 'emptied':
xs
=> Array [ <4 empty slots> ]
[...xs]
=> Array [ undefined, undefined, undefined, undefined ]
xs.length
=> 4
xs[0]
=> ReferenceError: reference to undefined property xs[0]
You can produce an equivalent array with [,,,,] or Array(4)

Losing the logic in my Javascript program

I have an issue with Javascript. I want to make the program , which generates 6 random numbers ( from 1 to 49 ).Anyway im doing it with for loop and it works. But when I try to find if any of those 6 numbers has a duplicate number , to replace it with a new random number. I've looked at js array duplicate functions , Im applying it , but it seems my fault is in the logic , still beginner with js , so please help me :)
js code:
var arr = new Array(7);
var numbers = [];
for(var i=1; i<arr.length;i++){
numbers[i] = Math.floor(Math.random()*48)+1;
if(numbers[i] == numbers[i+1]){
arr.indexOf(numbers[i]);
arr.push(Math.floor(Math.random()*48));
}
}
i`m trying to apply indexOf ( to find the duplicate number's index, and after that to replace it with new element via push()). Please give me some advises how to improve on my programming logic skills :(
First, JavaScript arrays are zero-indexed, so the first index is 0, not 1. Although it is valid to skip the first index and use the second to seventh indices instead, you will usually want to avoid that.
Second, why do you check numbers[i] against numbers[i + 1]? At that point, numbers[i + 1] won't have been set yet as it will be set in the next iteration. Additionally, even if this problem did not exist, your code would fail to catch this sequence: [ 5, 3, 5 ].
Third, I am not quite sure why you use two different arrays. Although you definitely can, there is no good reason to do so.
I will suggest another way to solve your problem and add comments to the steps necessary. I hope these will help you to understand this solution to your problem.
// Create an array for the chosen numbers
var numbers = [];
// Loop to generate 6 elements, zero-based
for(var i = 0; i < 6; i++) {
// This variable will hold the number we choose
var number;
// This is a do-while loop which generates a random integer
do {
// Generate a random integer between 1 and 49 (incl.)
number = Math.floor(Math.random() * 48) + 1;
} while(numbers.indexOf(number) != -1); // Exit loop once the number is not contained in the array
// Store the number in the array
numbers[i] = number;
}
This algorithm is short (8 SLOC) and pretty efficient.
This is one way you could do it:
var numbers = [];
for(i=0;i<6;i++){
numbers[i] = Math.floor(Math.random()*48)+1;
//this loop will help us check all of the already assigned numbers.
for(x=0;x<i;x++){
if(numbers[x] == numbers[i]){
i--;
}
}
}
This might not be the most efficient and optimal way to do it, but it sure works and it will give you no repetition on the numbers now that it will loop untill it finds a different number. Its a fast and short solution, yet not the most efficient. Hope this helps =).
for (var a=[],i=1;i<40;++i) a[i]=i;
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a);
Random Numbers , No repeats
This statement will never be true:
if(numbers[i] == numbers[i+1]){
When you start, numbers array is empty. Then you assign one random to element 0. Then you try to compare element 0 in numbers to 1, but numbers[1] will be undefined.
The best way to do this is to start with an empty arr array, meaning length of 0. Loop until length equals 6. In the loop, generate a random number and only push the value into the arr array if the number doesn't exist in there.
UPDATE:
After seeing some of the answers, I think this is probably the simplest:
var arr = [],
num;
while (arr.length < 6) {
num = Math.floor(Math.random() * 48) + 1;
if (arr.indexOf(num) === -1) {
arr.push(num);
}
}
console.log(arr);

Remove all items after an index

I have an array:
array = ['mario','luigi','kong']
I call its splice function to remove all items before an index:
array.splice(1) //-> ['luigi','kong']
I'm just wondering if there is a function similar to splice to remove all items after an index:
pseudo code
array.mirrorsplice(1) //-> ['mario','luigi']
Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";
Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and "returns" a number instead of a new array.
To address .splice usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";
Though assigning a shorter value to the array length(as #dandavis said) is the fastest and simplest way to remove trailing element from an array, you can also do that using a similar method like splice which is known as slice.
Like following:
array = ['mario', 'luigi', 'kong'];
array = array.slice(0, 2); //Need to assign it to the same or another variable
console.log(array); //["mario", "luigi"]
As you can see you need to store the returned value from slice method. To understand 'why', here are the major distinction between slice and splice method:
The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
To remove all items after an index:
var array = ['mario','luigi','kong'],
index = 1; // your index here
array = array.splice(index + 1, array.length - (index + 1) );
// 3 - (1+1) = 1
// 1 is the remaining number of element(s) in array
// hence, splice 1 after index
Result:
['mario', 'luigi']
You need to +1 since splice starts removing at the index.
I think you misunderstood the usage of Array.prototype.splice(). It already does what you asked for (remove everything after an index, read below paragraph for correction) and it does return the deleted values. I think you got confused with the returned value as the current value of the array.
Array.prototype.splice() however, removes the provided index value too, which is basically equivalent of setting the length of the array. So if you call it as array.splice(2), it'll set the length to 2 and everything including the values at index 2 and after will be deleted. This is provided that the current length of the array is greater than the first parameter provided to Array.prototype.splice().
For example:
const array = ['mario','luigi','kong'];
const deletedItem = array.splice(1);
console.log(array); // ['mario']
console.log(deletedItem); // ['luigi','kong']
For more information: refer to the MDN doc.
You can use splice. Here is a demo.
var array = ['mario','luigi','kong']
To remove all the elements after an index:
var removedElement = array.splice(index, array.length)
removedElement will have the list of elements removed from the array.
example:
let index = 2;
var removedElement = array.splice(2, array.length);
removedElement = ["kong"];
array = ["mario", "luigi"];

Categories