How to Dynamically Sort an Array of Objects in JavaScript

How to Dynamically Sort an Array of Objects in JavaScript

In this JavaScript tutorial show you how to dynamically sort an array of objects in JavaScript, using Array.prototype.sort() and a custom compare function.

If you have an array of objects that you need to sort into a certain order, you might be tempted to reach for a JavaScript library. But before you do, remember that you can do some pretty neat sorting with the native Array.sort function.

In this article, we’ll show you how to sort an array of objects in JavaScript with no fuss or bother.

Basic Array Sorting

By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order.

const foo = [9, 1, 4, 'zebroid', 'afterdeck'];
foo.sort(); // returns [ 1, 4, 9, 'afterdeck', 'zebroid' ]

const bar = [5, 18, 32, new Set, { user: 'Eleanor Roosevelt' }];
bar.sort(); // returns [ 18, 32, 5, { user: 'Eleanor Roosevelt' }, Set {} ]

You may be wondering why 32 comes before 5. Not logical, huh? Well, actually it is. This happens because each element in the array is first converted to a string, and "32" comes before "5" in Unicode order.

It’s also worth noting that unlike many other JavaScript array functions, Array.sort actually changes, or mutates the array it sorts.

const baz = ['My cat ate my homework', 37, 9, 5, 17];
baz.sort(); // baz array is modified
console.log(baz); // shows [ 17, 37, 5, 9, 'My cat ate my homework' ]

To avoid this, you can create a new instance of the array to be sorted and modify that instead. This is possible using an array method that returns a copy of the array. For example, Array.slice:

const sortedBaz = baz.slice().sort(); // a new instance of the baz array is created and sorted

Or if you prefer a newer syntax, you can use the spread operator for the same effect:

const sortedBaz = [...baz].sort(); // a new instance of the baz array is created and sorted

The output is the same in both cases:

console.log(baz); // ['My cat ate my homework', 37, 9, 5, 17];
console.log(sortedBaz); // [ 17, 37, 5, 9, 'My cat ate my homework' ]

Try it out

Using Array.sort alone wouldn’t be very useful for sorting an array of objects. Thankfully, the function takes an optional compareFunction parameter, which causes the array elements to be sorted according to the return value of the compare function.

Using Compare Functions to Sort

Let’s say that foo and bar are the two elements being compared by the compare function, and the return value of the compare function is set up as follows:

  1. less than 0 — foo comes before bar
  2. greater than 0  — bar comes before foo
  3. equal to 0  — foo and bar are left unchanged with respect to each other.

Let’s look at a simple example with an array of numbers:

const nums = [79, 48, 12, 4];

function compare(a, b) {
  if (a > b) return 1;
  if (b > a) return -1;

  return 0;
}

nums.sort(compare);
// => 4, 12, 48, 79

We can refactor this a little, as subtracting a from b will also give us the return value:

function compare(a, b) {
  return a - b;
}

This is now a good candidate for an arrow function:

nums.sort((a, b) => a - b);

How to Sort an Array of Objects in JavaScript

Now let’s look at sorting an array of objects. For this demo we’ll use an array of singers:

const singers = [
  { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
  { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
  { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
  { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];

We can use the following compare function to sort this array of singers according to their band:

function compare(a, b) {
  // Use toUpperCase() to ignore character casing
  const bandA = a.band.toUpperCase();
  const bandB = b.band.toUpperCase();

  let comparison = 0;
  if (bandA > bandB) {
    comparison = 1;
  } else if (bandA < bandB) {
    comparison = -1;
  }
  return comparison;
}

singers.sort(compare);

/* returns [
  { name: 'Steven Tyler', band: 'Aerosmith',  born: 1948 },
  { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
  { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
  { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 }
] */

To reverse the sorting order, you can invert the return value of the compare function:

function compare(a, b) {
  ...

  //invert return value by multiplying by -1
  return comparison * -1;
}

Try it out

Creating a Dynamic Sorting Function

Let’s finish up by making this more dynamic. Let’s create a sorting function, which you can use to sort an array of objects, whose values are either strings or numbers. This function has two parameters — the key we want to sort by and the order of the results (i.e. ascending or descending):

const singers = [
  { name: 'Steven Tyler', band: 'Aerosmith', born: 1948 },
  { name: 'Karen Carpenter', band: 'The Carpenters', born: 1950 },
  { name: 'Kurt Cobain', band: 'Nirvana', born: 1967 },
  { name: 'Stevie Nicks', band: 'Fleetwood Mac', born: 1948 },
];

function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
      // property doesn't exist on either object
      return 0;
    }

    const varA = (typeof a[key] === 'string')
      ? a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string')
      ? b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
      comparison = 1;
    } else if (varA < varB) {
      comparison = -1;
    }
    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

And this is how you’d use it:

// array is sorted by band, in ascending order by default
singers.sort(compareValues('band'));

// array is sorted by band in descending order
singers.sort(compareValues('band', 'desc'));

// array is sorted by name in ascending order
singers.sort(compareValues('name'));

// array is sorted by date if birth in descending order
singers.sort(compareValues('born', 'desc'));

Try it out

In the code above, the hasOwnProperty method is used to check if the specified property is defined on each object and has not been inherited via the prototype chain. If it’s not defined on both objects, the function returns 0, which causes the sort order to remain as is (i.e. the objects remain unchanged with respect to each other).

The typeof operator is also used to check the data type of the property’s value. This allows the function to determine the proper way to sort the array. For example, if the value of the specified property is a string, a toUpperCase method is used to convert all its characters to uppercase, so character casing is ignored when sorting.

You can adjust the above function to accommodate other data types, and any other needs your script may have.

String.prototype.localeCompare()

In our example above, we want to be able to sort an array of objects, whose values are either strings or numbers. If, however, you know that you’ll only be dealing with objects whose values are strings, you can tidy up the code a little using JavaScript’s localeCompare method.

This method returns a number indicating whether a string comes before, after, or is the same as a given string in the sort order. It enables a case-insensitive sort of an array:

['bjork', 'Bjork', 'Björk'].sort();
// [ 'Bjork', 'Björk', 'bjork' ]

['bjork', 'Bjork', 'Björk'].sort((a, b) => a.localeCompare(b));
//  [ 'bjork', 'Bjork', 'Björk' ]

In terms of our compareValues function, that means we could write:

function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0;
    const comparison = a[key].localeCompare(b[key]);

    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

You can read more about localeCompare over on MDN.

Conclusion

So there you have it — a short introduction to sorting an array of objects using vanilla JavaScript. Although many libraries offer this kind of dynamic sorting ability, as demonstrated, it’s not all that hard to implement this functionality yourself. Plus it’s good to understand what is going on under the hood.

JavaScript ES6 Classes

JavaScript ES6 Classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

Classes are a fundamental part of object oriented programming (OOP). They define “blueprints” for real-world object modeling and organize code into logical, reusable parts. Classes share many similarities with regular objects. They have their own constructor functions, properties, and methods. In this tutorial, we’ll demonstrate how to create and work with ES6 classes.

Creating a class

You can create a class using the class keyword:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }

}



let person = new Person("Sam", 30)



person.name

//returns 'Sam'



person.age

//returns 30

Notice how we define our Person class with a constructor() function taking two arguments name and age. Using the this keyword, we set the name and age properties based on the provided arguments. Remember that the constructor function is called whenever we create a new instance of the Person class.

Similar to objects, we can read class properties using dot notation so that person.name returns Sam.

Defining properties and methods

You can define properties and methods for a class the same way you do for regular objects:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



let person = new Person('Tim', 40)



person.sayName()

//logs 'My name is Tim'



person.location = 'London'



person.location

//returns 'London'

Notice how we define a sayName() function within our Person class definition. Once we create a new instance of Person, we can call the method via person.sayName().

You can also add properties and methods on the fly. You’ll notice that while the location property isn’t defined in our constructor function, we can still dynamically add it later on for the person instance. Remember that if we created a new instance of Person, it would not have a location property because that property is not defined in the class definition. Only properties and methods that we explicitly define will be shared by all instances of the class.

Static functions

You can use the static keyword to make class methods static. A static method acts on the class itself, not on instances of the class:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



Person.describe()

//logs 'This is a person.'

Notice how static methods operate on the class itself and not an instance of the class. We didn’t have to create a new Person to call the static method.

Static methods are useful for common or shared class functionality. In this case, the describe() method is used to describe what the Person class is. It will apply to every instance of Person. This is why we make it a static method.

Class Inheritance

Inheritance allows you to create new classes based off existing ones. These new classes “inherit” the methods and properties of their parent. They can also override or extend the parent:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }


  static describe(){

    console.log("This is a person.")

  }


  sayName() {

    console.log("My name is " + this.name)

  }

}



class Programmer extends Person {

  sayName(){

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



averageJoe.sayName()


//logs 'My name is Todd'


programmer.sayName()


//logs 'My name is Sam and I am a programmer!'

Using the extends keyword, we can create a new class sharing the same characteristics as Person. Notice how we override the sayName() method with a new definition for the Programmer class. Apart from overriding this method, everything else remains the same for both Person and Programmer.

Using super

The super keyword allows a child class to invoke parent class properties and methods.

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}





class Programmer extends Person {

  sayName(){

    super.sayName()

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



programmer.sayName()



//logs 'My name is Sam'

//logs 'My name is Sam and I am a programmer!'

Notice how we call super.sayName() in the Programmer implementation of sayName(). While this invokes the parent implementation of super.sayName(), the name property still references the Programmer class.

Conclusion

Classes facilitate object oriented programming in JavaScript. While regular objects provide similar functionality, classes provide the extra advantage of inheritance and static methods.

Javascript ES6: Map-Reduce-Filter-Find

Javascript ES6: Map-Reduce-Filter-Find

If you are a fan of javascript and use it daily then you will love this. Way you write your JavaScript by using .map(), .reduce() and .filter() ... concise with arrow functions

If you are a fan of javascript and use it daily then you will love this

Javascript is a language that give freedom of writing code in any style, from imperative to declarative styles. Most programmer use imperative because either they are coming from OOPs background, may be they love it or they are not familiar with other style. Before we dive into the declarative style which is FP, let’s understand the differences in two by looking at an example(If you already know the difference then you may skip few paragraphs).

Imperative

// to calculate the sum of array elements
const sum = (arr) => {
  let result = 0; 
  for (let i = 0; i < arr.length; i++) {
    result += arr[i];
  }  
  return result;
};

Imperative style is cool but imagine what if there is a complex mathematics logic here then size of code and the readability will suck. It increases the cognitive load when reading, and over time makes it easier to faulter in reasoning and logic. Also, the main complexity of this code snippet derives from the fact that instead of telling the computer what we want it to do, we are instructing it on how to do it.

Declarative

// calculate the sum of array elements
const sum = (arr) => arr.reduce((total, item) => total += item, 0);

Now, this looks pretty clean, shorter, expressive, concise code, less error prone, easier to maintain and easier to debug. We are telling computer what we want it to do rather how to do it.

Declarative approach are easily optimisable at complier end and also have less side effects.

Note: if you are concerned about the performance of above two and other javascript function (map, reduce, filter, find) then you should for small data set and can view here for large data set(100–1000000)

Without more delay, let’s start the real action with most used Javascript function for functional programming.

Map

// definition 
collection.map((currentValue, index) => {
    // Return element for newArray
});
// example
const arr = [1,2,3,4,5];
const newArray = arr.map(i => i*10);
// return a new array with all value as multiple of 10;

Map works on an array and return an array that’s it. Above code snippet works on an collection i.e an array and takes a callback with current iteration value, index as arguments and return a new array.

Note: Maps are well suited for change/transforming whole array rather than breaking the flow for some conditions, Map suck’s performance wise, check out "underlined" here but are easy to be used for small data sets.

Reduce

// definition 
collection.reduce((accumulator, item, index) => {
    // logic to perform to get accumulator as a return value
}, initialValue for accumulator);
// example
const arr = [1,2,3,4,5];
const total = arr.reduce((acc, item) => acc+= item, 0);
// return a total as 15

Reduce works on an array but can return anything you want it to return. As the name speaks for itself it can be reduce to anything and can behave like map, find, filter or any other javascript function. The above code snippet works on an array and reduce to compute the total value of item of array.

Explanation of example above : On reduce first run, acc is assigned a 0 value and then acc+= item i.e acc = acc+item which will compute to0+1 i.e 1. This 1 will be acc value for next iteration and this continues until we are done with all array items.

Find

// definition 
collection.find((item) => {
    // return first element that satisfy the condition
});
// example
const arr = [1,2,8,4,5];
const value = arr.find(i => i%4 == 0);
// return the first value i.e 8 

Find works on an array and return the first element that satisfy the condition in function.

Note: Easy, simple but not efficient on large data set, why ? look here

Filter

// definition 
collection.filter((currentValue, index) => {
    // logic to filter array on
});
// example
const arr = [1,2,3,4,5];
const newArray = arr.filter(i => i%2 == 0);
// return a new array with value [2, 4]

Filter works on array return an array for filtered items.


Lets use them for some real world scenarios + some ES6. (lets try some ARMD on below object keys)

Wondering what is ARMD its Add, Read, Modify, Delete, its cool to coin your own jargon

const users = [
  {
    id: 1,
    name: "Jonathon Haley",
    username: "Monte.Weber2",
    email: "[email protected]",
    phone: "1-563-675-1857 x11708",
    website: "carmela.net",
    password: "hashed_password"
  },
  {
    id: 2,
    name: "Dean John",
    username: "dd.1",
    email: "[email protected]",
    phone: "1-123-543-1857 123212",
    website: "dd.net",
    password: "Dean_hashed_password"
  }

We will use users as array for further examples

1. ARMD — Adding a new element to users

const newUser = {
    id: 4,
    name: "Denomer Crazy",
    username: "crazy.1",
    email: "[email protected]",
    phone: "",
    website: "crazy.app",
    password: "crazed_checker"
};
const newData = [...users, newUser]; // add element at last
or 
const newData = [newUser, ...users]; // add element at first
or 
const newData = users.concat(newUser) // the old way

The use of es6 spread operator make super easy to add elements to array. We can use spread operator to concat two different array, modify shape of objects or add dynamic key value pairs etc.

const hobbies = ['chess', 'pool'];
const newUsers = users.map(u => ({...u, hobbies}))
// this will add hobbies to users array and return newUsers array

2. ARMD — Get email address, phone number and website of users into new array

const contactInfo = users.map(({email, website, phone}) => ({email, website, phone}));

The use es6 of destructuring of object keys and map to get the contact info array for user.

3. ARMD — Find and replace value for key of objects

const newUsers = users.map(u => u.id == 2? ({...u, name: 'te'}): u);
// this will return newUsers with all user having name 'te'

4. ARMD —Delete some key’s from object

Note: We will actually not delete the key but return a new object, if you want to delete the key use delete operator, here we are considering object immutability.

To delete keys there are lot of ways but we will look at the most easy, single lined. Lets try to delete website from users.

const newUsers = users.map({id, email, name, username, phone, password} => ({id, email, username, email, phone, password}));
// will return an array with all keys other than website

Above code seems to be practically difficult to code for big objects.

const newUsers = users.map(u => Object.keys(u).reduce((newObj, key) => key != 'website' ? { ...newObj, [key]: u[key]} : newObj, {}));

We map through the users and then on each user we do a reduce and form a new object (newObj) and then check for website key, if its a website we return the previously formed newObj, if not then we do a spread operator and add require key to obj and finally return newObj.

If anything is not clear or you want to point out something, please comment down below.

Thank you

20 Fastest Methods to Easily identify Array's Operation in JavaScript

20 Fastest Methods to Easily identify Array's Operation in JavaScript

In this post, I'll show you 20 Methods to Get to Know JavaScript Array Operations

Methods to Get to Know JavaScript Array Operations

For example, Let’s create an Array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];
1. Filter

The filter() method creates a new array with elements that return true from the callback function.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

var vegFoods = foods.filter( (food) => isVeg(food) );

vegFoods; ["🍎", "🍊", "🍕"];
2. lastIndexOf

First last index of a given element in the Array, if it is not present, it returns -1.

var foods = ["🍎", "🍊", "🍗", "🍕", "🥩", "🍎"];

foods.lastIndexOf('🍎'); // 5

foods.lastIndexOf('🍔'); // -1
3. Length

Returns the number of an element of the Array.

foods.length; // 5

Tip: We can change the length property to delete elements.

foods.length = 0;

foods; // []
4. Push

Add an element to the end of an Array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.push('🍇');

foods; // ["🍎", "🍊", "🍗", "🍕", "🥩", "🍇"]

Tip: Use push with the spread operator () as an alternative to the concat method.

var numbers = [1,2,3,4,5];

var num2 = [6,7,8,9,10];

numbers.push(...num2);
5. Unshift

Add an element to the beginning of an Array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.unshift('🍇');

foods; // ["🍇", "🍎", "🍊", "🍗", "🍕", "🥩"]

Tip: Use unshift with the spread operator () to concat elements at the beginning.

var numbers = [1,2,3,4,5];

var num2 = [6,7,8,9,10];

numbers.unshift(...num2);
6. Pop

Removes the last element of the array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.pop();  // "🥩"

foods; // ["🍎", "🍊", "🍗", "🍕"]

Tip: We can use the pop method in stack implementation.

7. Shift

Remove the first element of the array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.shift();  // "🍎"

foods; // ["🍊", "🍗", "🍕", "🥩"]

Tip: We can use the shift method in dequeue operations on Queue implementation.

8. Join

Joins the elements of Array to String.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

var joinedFood = foods.join(); // "🍎,🍊,🍗,🍕,🥩";

var joinedFood1 = foods.join('--'); // "🍎--🍊--🍗--🍕--🥩"

Tip: Use as an alternative to string concatenation.

var arr = ['J','a','v', 'a'];

var str = '';

// without join

for(let i = 0, len = arr.length; i < len ; i++) {

     str += arr[i];
		 
}

// with join

str = arr.join(''); // Java
9. Concat

Concat an Array with arguments.

var array = [1,2,3,4,5];

var newArray =  array.concat(1,2,3, [12,12,34], undefined, null);

newArray; // [1, 2, 3, 4, 5, 1, 2, 3, 12, 12, 34, undefined, null]
10. Reverse

Reverse the elements of the array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.reverse();

foods; // ["🥩", "🍕", "🍗", "🍊", "🍎"]

Tip: Reversing string.

var str = "Anitha";

var strArray = [...str].reverse().join('');
11. indexOf

First index of a given element in the Array, if it is not present, it returns -1.

var foods = ["🍎", "🍊", "🍗", "🍕", "🥩", "🍎"];

foods.indexOf('🍎'); // 0

foods.indexOf('🍔'); // -1
12. Some

Checks if any of the elements return true from the callback function.

var num = [1,2,3,4,10, 12];

num.some(n => n > 10); // true

num.some(n => n > 100); // false
13. Every

Check if all of the elements return true from the callback function.

var num = [1,2,3,4,10, 12];

num.every(n => n > 10); // false

num.every(n => n > 0); // true
14. Sort

Sort the elements of the array. By default, it sorts based on char code. We can also pass our sort function.

var arr = ['b', 'c', 'd', 'e'];

arr.sort(); // ["b", "c", "d", "e"]

// custom sort

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

arr.sort( (a, b) => a-b ); // [1, 2, 3, 4, 5, 11]

Be careful using the sort method, because it sorts based on char code, in which “11" < “2”.

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

arr.sort();  [1, 11, 2, 3, 4, 5]

Tip: Shuffle an Array with sort.

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

arr.sort( () => Math.random() - 0.5);
15. Reduce

The reduce() method executes a reducer function (which you provide) on each element of the array, resulting in a single output value.

Example one:

var apples = ["🍎", "🍎"];

var juice = 🧃 ;  // think as empty can 

function makeJuice(juice, fruit) {

    let fruitMix = grind(fruit);
		
    return fruitMix + juice;
		
}

apples.reduce( makeJuice , juice);

Example two:

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

var result = 0;

function add(res, currentNum) {
   return res + currentNum;
	 
}

arr.reduce(add, result);
16. ReduceRight

Similar to reduce but elements are passed to the callback function from right to left.

var array = [1,2,3,4,5];

function sum(result, num) {

   console.log(num);
	 
   return result + num;
	 
}

var result = 0;

array.reduce(sum, result);

// go from left to right i.e., 1,2,3,4,5

array.reduceRight(sum, result);

// go from right to left i.r., 5,4,3,2,1
17. Map

Creates a new Array from the value returned by the callback function, which is executed for every element of the Array.

var numbers = [1,2,3,4,5];

function double(num) {
   return num * num;
}

var doubledNumbers = numbers.map(double) 
18. Splice

The splice() method will remove n number of elements from the specific index and also inserts the elements.

var array = [1,2,4,5];

array.splice(2, 0, 3); //insert 3 at index 2

array;  // [1,2,3,4,5]

array.splice(2, 1, 30);//remove 1 item from index 2 and insert 30

array; // [1, 2, 30, 4, 5]

Tip: Use this method to inset an element at a specific index.

function insertElementAtIndex(array, index, elem) {
   array.splice(index, 0, elem);
}
19. Slice

The slice() method returns a shallow copy of a portion of an Array.

var array = [1,2,3,4,5];

array.slice(1); // [2, 3, 4, 5] --> slice starts from index 1 to end

array.slice(1,3); // [2,3]--> slice from index 1 to (3-1)

Tip: Get last element of the array:

// get last n elements

array.slice(-n);

n = 1

array.slice(-1); 5

if n = 3

array.slice(-3); //  [3, 4, 5];
20. forEach

Executes a callback function once for each Array element. We cannot use break and continue in forEach, map functions.

var numbers = [1,2,3,4,5]

numbers.forEach((e) => {

  console.log(e)
	
});

Thank you for reading !