-2

How to delete values from array after index ?

 var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];

I tried like using slice():

 var new_array = fruits.slice(2);

 // console.log(new_array ) prints
 [15, 20, 25, 30, 35, 40, 45, 50, 55, 60]

But i want the output to delete all values in array after index

And expected output of the array is :

 [5,10,15]
Scimonster
  • 30,695
  • 8
  • 67
  • 84
ram
  • 1,995
  • 3
  • 23
  • 37

2 Answers2

1

You need to use slice(0,3) to slice out between indexes 0 and 3, obtaining indexes 0,1,2. That's [5,10,15].

Scimonster
  • 30,695
  • 8
  • 67
  • 84
0

You seem to just want to truncate the array. The simplest way is to set its length:

array.length = 3;

If you were doing that based on an index (say, index = 2), you'd add one to get the length, as arrays are 0-based:

array.length = index + 1;

If you want to get a copy a subset of elements as a new array, you would indeed use slice:

var new_array = array.slice(0, 3);

Live example of truncation:

var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];
snippet.log("Before: " + array.join(", "));
array.length = 3;
snippet.log("After: " + array.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Live example of copy:

var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];
snippet.log("array: " + array.join(", "));
var new_array = array.slice(0, 3);
snippet.log("new_array " + new_array.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639