-1

I have list of arrays in an array. I need to pick first 3.

For example i have this :

[{[1]},{[2]},{[3]},{[4]}]

Sorry i know it's not a proper array i am attaching my console

enter image description here

This is my arrays look like and i need to pick just first 3 . And also can i restructure my array like this in one array ?

[{1},{2},{3}]
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
UmaiZ
  • 93
  • 6
  • 18

3 Answers3

2

You can either use slice

array.slice(0, 3);

if you want to modify the original array use,

arr.length = 3;

Demo :

var arr = [1, 2, 3, 4];

var newArr = arr.slice(0,3);

console.log(newArr);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

A good function is to use the slice function from array. An example looks like this:

  var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
  var citrus = fruits.slice(0, 3);

The result will be citrus = Banana,Orange,Lemon

Mark Holst
  • 19
  • 2
0

If you want to change the original array use splice(); e.g.

    let array=['1','2','3','4','5'];
array.splice(3);
 array; // 1,2,3;

But if you want that changes should not reflect original array use slice() method.

    let array=['1','2','3','4','5'];
let finalArray=array.slice(0,3);
 array; // 1,2,3,4,5;
finalArray; // 1,2,3;