I have a list of array I only need last element in array.
For example.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
My Required result is ["Mango"].
I have a list of array I only need last element in array.
For example.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
My Required result is ["Mango"].
You can use pop()
at the simplest level to get the last element only and assign that value as an array to the original array. Unlike splice
you do not need to worry about calculating the length value of the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits = [fruits.pop()];
console.log(fruits)
You can access it with his index and the array length
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits = [fruits[fruits.length-1]];
console.log(fruits)
You can access last index of array by getting array length and accessing last index.
var array = [1,2,3,4,5,6];
var val = array[array.length - 1]; // 6
This is another way you can get last index:
<html>
<head>
<title>Get the last element in an Array</title>
<script language="javascript" type="text/javascript">
<!--
var x = new Array(2,3,4);
alert(x[x.length-1]);
//-->
</script>
</head>
<body>
</body>
</html>
You could take Array#slice
with a negative value, from the end, and return an array of the last item.
Slicing does not mutate the original array.
var fruits = ["Banana", "Orange", "Apple", "Mango"],
wanted = fruits.slice(-1);
console.log(wanted);
You can get the last element of an array with the following methods:
1st:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fruits = fruits.slice(-1)[0];
console.log(fruits);
2nd:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fruits = fruits[fruits.length-1];
console.log(fruits);