Some good and important concept of search, delete and sort

← Go back

Searching with Multiple Parameters

You can use the filter() method to search through an array with multiple parameters. For example, if you have an array of objects and want to search based on multiple properties:

let array = [ 
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 25 }
];

let searchResults = array.filter(item => item.name === 'Alice' && item.age === 25);
console.log(searchResults); // [{ id: 1, name: 'Alice', age: 25 }]


Sorting with Multiple Parameters

​You can use the sort() method along with a custom compare function to sort an array with multiple parameters. For example, to sort first by age, and then by name:

let array = [ 
{ id: 1, name: 'Charlie', age: 25 },
{ id: 2, name: 'Alice', age: 30 },
{ id: 3, name: 'Bob', age: 25 }
];

array.sort((a, b) => {
if (a.age === b.age) {
return a.name.localeCompare(b.name); // Sort by name if ages are equal
}
return a.age - b.age; // Sort by age
});

console.log(array);
// [
// { id: 3, name: 'Bob', age: 25 },
// { id: 1, name: 'Charlie', age: 25 },
// { id: 2, name: 'Alice', age: 30 }
// ]


Deleting Specific Array Element by ID

To delete a specific array element by id, you can use the filter() method:

let array = [ 
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 25 }
];

let idToDelete = 2;
let updatedArray = array.filter(item => item.id !== idToDelete);
console.log(updatedArray); // [{ id: 1, name: 'Alice', age: 25 }, { id: 3, name: 'Charlie', age: 25 }] ​