Reputation: 175
How can I select on certain values and sort them alphabetically using ES6. The current codes defines a constant. I wanted to know if I could manipulate this data without having to create a new constant with just the values I need.
export const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris'
};
Return only Chris and David.
Chris
David
Upvotes: 1
Views: 124
Reputation: 404
const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris',
};
const searchNames = (args, search) => {
const arr = Object.values(args);
const result = arr.filter(n => {
return search.includes(n);
});
return result.sort().join('\n');
};
searchNames(names, ['David', 'Chris']);
// returns: Chris
// David
Not the most elegant, but it works. It would be easier to start with an array instead of an object. It doesn't seem like the object is necessary since the keys and values are identical. Nonetheless, this is a pretty easy task with an array. I converted the obj to an array containing only the values. Then created a new array
filtering out the names we wanted, returned that array sorted alphabetically and in a string format. The ('\n')
in the return statement is just delimiting the elements of the array by a new line, since that's the format you showed. But that can be changed to anything, if you don't need the names to be on separate lines.
Just to clarify, as per the documentation, const can be used here:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.
Upvotes: 3
Reputation: 604
Yes you can manipulate this data, have a look on how const works in javascrips. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
const names = {
John: 'John',
Mike: 'Mike',
David: 'David',
Chris: 'Chris'
};
console.log(names.John);
names.John = 'noJohn';
console.log(names.John);
Upvotes: -1