Thursday, December 7, 2023
HomeSoftware EngineeringMethods to Type an Array of Objects by Property in Javascript

Methods to Type an Array of Objects by Property in Javascript


If you have to kind an array of objects by their property values utilizing Javascript, then you definately don’t must look additional than the built-in kind performance.

Step 1 – Create an array of objects to work with

let folks = [
    {
        name : "John",
        surname : "Doe",
        age : 21
    }, {
        name : "Jack",
        surname : "Bennington",
        age : 35
    }, {
        name : "Jane",
        surname : "Doe",
        age : 19
    }
];

Step 2 – Type by keys

Possibility 1 – Type by surname

folks.kind((a, b) => a.surname.localeCompare(b.surname));
console.log(folks);

This offers you the next output:

[
  {name: 'Jack', surname: 'Bennington', age: 35},
  {name: 'John', surname: 'Doe', age: 21},
  {name: 'Jane', surname: 'Doe', age: 19}
]

Possibility 2 – Type by age

folks.kind((a, b) => {
    return a.age - b.age;
});
console.log(folks);

This offers you the next output:

[
  {name: 'Jane', surname: 'Doe', age: 19},
  {name: 'John', surname: 'Doe', age: 21},
  {name: 'Jack', surname: 'Bennington', age: 35}
]
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments