DEV Community

Keerthana M
Keerthana M

Posted on

Basic Array Models.(part2)

JavaScript Array shift()

  • The shift() method removes the first array element and "shifts" all other elements to a lower index.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
console.log(fruit);
console.log(fruits);

Output:
Banana
['Orange', 'Apple', 'Mango']

JavaScript Array unshift()

  • The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements
  • The unshift() method returns the new array length:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
console.log(fruits);

Output:

['Lemon', 'Banana', 'Orange', 'Apple', 'Mango']

Array.isArray():

  • Array.isArray() is used to check the array is in array form or not.
  • It returns the value in true or false.

const fruits = ["Banana", "Orange", "Apple"];
let fruit = Array.isArray(fruits);
console.log (fruit);

Output:
True

JavaScript Array concat():

  • The concat() method creates a new array by merging (concatenating) existing arrays:

  • concatenation means joining strings end-to-end.

const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
console.log(myChildren);

Output:
['Cecilie', 'Lone', 'Emil', 'Tobias', 'Linus']
Array copyWithin():

  • The copyWithin() method copies array elements to another position in an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
console.log(fruits);

Output:
['Banana', 'Orange', 'Banana', 'Orange']
JavaScript Array flat():

  • The flat() method creates a new array with sub-array elements concatenated to a specified depth.
  • Flattening an array is the process of reducing the dimensionality of an array.
  • Flattening is useful when you want to convert a multi-dimensional array into a one-dimensional array.

const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
console.log(newArr);

Output:
 [1, 2, 3, 4, 5, 6]

Top comments (0)