Reputation: 9583
I want to know how to use destructured multiple arguments given to a function when both parameters are of same type.
For example, consider I have the following code:
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by name
items.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
Now, as you can see, only the name
properties of a
and b
objects have been used in the function. So how will I use object destructuring to alter the code, something like this:
items.sort(({name}, {name}) => {
// code to use
});
Upvotes: 0
Views: 260
Reputation: 138567
You can assign another name during destructuring:
items.sort(({name : A}, {name : B}) =>
A.toUpperCase().localeCompare(B.toUpperCase())
);
(And you can use localeCompare instead of your if else logic)
Upvotes: 4