-1

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

Gaurav Kandpal
  • 1,250
  • 2
  • 15
  • 33

6 Answers6

2

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)
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

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)
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32
0

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
0

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>
0

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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);
Zobia Kanwal
  • 4,085
  • 4
  • 15
  • 38