Remove all items after an index - javascript

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"];

Related

Why is .splice(1, 0, '.') returning an empty array? (Javascript)

Here is my code:
let num = 0.0134;
console.log(num.toString().split('').splice(3).splice(1, 0, '.'))
The console.log returns an empty array.
I want it to return '1.34'. What am I doing wrong?
If you see the reference for Array.prototype.splice on mdn:
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
Return Value: An array containing the deleted elements.
At the end of your code, when you do .splice(1, 0, '.'), it deletes 0 elements so it will return an empty array.
I'm assuming you want to get the previous array with the '.' element inserted in the first position. For that you'll want to do:
const arr = num.toString().split('').splice(3);
arr.splice(1, 0, '.');
console.log(arr)
And If you want to join it to a string just use arr.join('')
Anyway, for your use case, you could just use the * multiplication operator rather than converting to a string array and attempting to manipulate that.
You can simply do:
let num = 0.0134;
console.log(num * 100);

How do I add an item to the middle of an array?

function reverse(array,item){
let word = Math.ceil(array.length/2)
return array.splice(word,0,item)
}
console.log(reverse([1,2,4,5,6],3))
I was wondering why I'm getting a an empty array when the I call the function, instead of [1,2,3,4,5,6]?
Array#splice returns the items of the second parameter's count, the items who are deleted.
For returning the array, you need to return then array and not the spliced items.
function reverse(array, item) {
let word = Math.ceil(array.length / 2);
array.splice(word, 0, item);
return array;
}
console.log(reverse([1, 2, 4, 5, 6], 3));
splice does not return a new array, it modifies the input array. you need to return explicitly
function reverse(array,item){
let word = Math.ceil(array.length/2)
array.splice(word,0,item)
return array
}
console.log(reverse([1,2,4,5,6],3))
array.splice(...) does not return a new array, it modifies the input array. Per MDN, its return value is:
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
If your intention is to create a function that inserts without modifying the original array, here's a good example: https://stackoverflow.com/a/38181008/1266600.
splice() changes the original array whereas slice() doesn't.
If you don't want to alter the original array, use slice.
function reverse(array,item){
let word = Math.ceil(array.length/2)
return [].concat(array.slice(0,word - 1), item, array.slice(word - 1));
}
console.log(reverse([1,2,4,5,6],3))

how to find last value of array using javascript?

I have an array in javascript. I have to find last value of that array.
My code is like
var array= fruits;
and I have to find last fruit in that array.
Since in JavaScript arrays of size n are indexed from [0..n-1], you can get the last element by simply indexing the array at n-1, where is the length of the array and can be obtained by the .length property:
var lastFruit = array[array.length - 1];
If you want to get the last element and also remove it from the array, you can use the .pop methid:
var lastFruit = array.pop(); // get last element of array and remove it from array
Note: As RobG stated:
length is at least one more than the highest index, but might be
greater
First find number of elements in array and store it on variable like
var total = array.length;
Now you can find last value of array using below code
var last = array[total-1];
You accomplish this by using the length of the array (fruits.length) and subtracting 1 (because the array is 0 indexed). For instance...
fruits[0]="pear";
fruits[1]="apple";
fruits[2]="peach";
So fruits.length would be 3, so fruits.length - 1 = 2. So to get the last element...
var lastFruit = fruits[fruits.length-1];
I have to find last value of that array
The length property is at least one higher than the highest index, however it might be higher in which case the n-1 member may not exist. E.g.
// Create an array with length 10
var a = new Array(10);
// Add one member at index 0
a[0] = 'foo';
So the "last" value of the array is at index 0 and has a value of "foo". So you can start with length - 1 and search backwards for members that actually exist:
function lastValue(arr) {
var i = arr.length;
while (i--) {
if (i in arr) {
return arr[i];
}
}
// If get to here, arr has no members
return -1;
}
// All the following arrays have length 4 but different number of members
console.log(lastValue([ , , , ,])); // -1, i.e. there are no members
console.log(lastValue([0,1, , ,])); // 1
console.log(lastValue([0,1,2,3 ])); // 3
console.log(lastValue([ , , ,3 ])); // 3
If you know the Array only has numeric members (i.e. there are no non-numeric properties and no negative properties) you can do:
var arr = [,,'foo',,'bar',,]; // length 6, highest member is at index 4
console.log(arr[Math.max.apply(Math, Object.keys(arr))]); // 'bar'
Requires ES5 Object.keys.
Well you can find it's length then you know the last index, and can get the item from it
var last_item = array[array.length - 1];
Its as easy as:
fruits[fruits.length-1]

Can I limit the length of an array in 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);

Javascript Array Problem

Why is JavaScript returning the wrong array length?
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
The "delete" doesn't modify the array, but the elements in the array:
# x = [0,1];
# delete x[0]
# x
[undefined, 1]
What you need is array.splice
you have to use array.splice - see http://www.w3schools.com/jsref/jsref_splice.asp
myarray.splice(0, 1);
this will then remove the first element
According to this docs the delete operator does not change the length ofth earray. You may use splice() for that.
From Array's MDC documentation:
"When you delete an array element, the
array length is not affected. For
example, if you delete a[3], a[4] is
still a[4] and a[3] is undefined. This
holds even if you delete the last
element of the array (delete
a[a.length-1])."
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array
You can do this with John Resig's nice remove() method:
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
than
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
That's the normal behavior. The delete() function does not delete the index, only the content of the index. So you still have 2 elements in the array, but at index 0 you will have undefined.

Categories