Dec 28, 2020

JAVASCRIPT ARRAY METHODS

 

JAVASCRIPT ARRAY METHODS


Creating an array of objects:

let cars = [
  {
    "color": "purple",
    "type": "minivan",
    "registration": new Date('2017-01-03'),
    "capacity": 7
  },
  {
    "color": "red",
    "type": "station wagon",
    "registration": new Date('2018-03-03'),
    "capacity": 5
  },
  {
    ...
  },
  ...
]


To add an object at the first position, use Array.unshift.

let car = {

  "color": "red",

  "type": "cabrio",

  "registration": new Date('2016-05-02'),

  "capacity": 2

}

cars.unshift(car);


Add a new object at the end - Array.push

let car = {

 "color": "red",

 "type": "cabrio",

 "registration": new Date('2016-05-02'),

 "capacity": 2

}

cars.push(car);


Add a new object in the middle - Array.splice

    Array.splice( {index where to start}, {how many items to remove}, {items to add} );

let car = {

  "color": "red",

  "type": "cabrio",

  "registration": new Date('2016-05-02'),

  "capacity": 2

}

cars.splice(2, 0, car);


Find an object in an array by its values - Array.find

let car = cars.find(car => car.color === "red");

let car = cars.find(car => car.color === "red" && car.type === "cabrio");


Get multiple items from an array that match a condition - Array.filter

let redCars = cars.filter(car => car.color === "red");

console.log(redCars);



Add a property to every object of an array - Array.forEach

cars.forEach(car => {

 car['size'] = "large";

 if (car.capacity <= 5){

   car['size'] = "medium";

 }

 if (car.capacity <= 3){

   car['size'] = "small";

 }

});


Sort an array by a property - Array.sort

let sortedCars = cars.sort((c1, c2) => (c1.capacity < c2.capacity) ? 1 : 

                                      (c1.capacity > c2.capacity) ? -1 : 0);

console.log(sortedCars);

 

Checking if objects in array fulfill a condition - Array.every, Array.includes

Array.every and Array.some come handy when we just need to check each object for a specific condition.

cars.some(car => car.color === "red" && car.type === "cabrio");

// output: true

cars.every(car => car.capacity >= 4);

// output: false 



Reference Link : click Here 

No comments:

Post a Comment