So I have an array
of objects
like:
[
{ letter: 'A', title: 'All' },{ letter: 'B', title: 'Business' },
{ letter: 'G', title: 'Cor' },
{ letter: 'G', title: 'Car' },
]
How can I sort it so it looks like this:
[
{ letter: 'A', title: 'All' },
{ letter: 'B', title: 'Business' },
{ letter: 'G', title: 'Cor', 'Car' },
]
CodePudding user response:
Something like this would work
const original = [
{ letter: 'A', title: 'All' },
{ letter: 'B', title: 'Business' },
{ letter: 'G', title: 'Cor' },
{ letter: 'G', title: 'Car' },
];
const map = {};
original.forEach(({letter, title}) => {
if(!Object.hasOwnProperty.call(map, letter)) map[letter] = {letter, title: [title]};
else {
map[letter]?.title.push(title);
}
});
console.debug(Object.values(map));
CodePudding user response:
You can do sort
followed by filter
.
const data = [{
letter: 'A',
title: 'All'
}, {
letter: 'B',
title: 'Business'
}, {
letter: 'G',
title: 'Cor'
}, {
letter: 'A',
title: 'Car'
}];
data.sort(function (a, b) {
if (a.letter < b.letter) {
return -1;
}
if (a.letter > b.letter) {
return 1;
}
return 0;
})
const result = data.filter((v, i, a) => a.findIndex(t => (t.letter === v.letter)) === i)
console.log(result)
CodePudding user response:
You could use Array.sort()
to sort the input array by letter, then use Array.reduce()
along with a Map
object to group the input by letter:
const input = [
{ letter: 'Z', title: 'Title Z' },
{ letter: 'A', title: 'All' },
{ letter: 'B', title: 'Business' },
{ letter: 'G', title: 'Cor' },
{ letter: 'G', title: 'Car' },
];
const sortedInput = input.sort(({ letter: a},{ letter: b}) => a.localeCompare(b));
const result = [...sortedInput.reduce((acc, { letter, title }) => {
return acc.set(letter, { letter, title: [...(acc.get(letter)?.title || []), title] } );
}, new Map()).values()];
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
You could sort first and then reduce the array.
const
data = [{ letter: 'A', title: 'All' }, { letter: 'B', title: 'Business' }, { letter: 'G', title: 'Cor' }, { letter: 'G', title: 'Car' }],
result = data
.sort((a, b) => a.letter.localeCompare(b.letter))
.reduce((r, o) => {
if (r[r.length - 1]?.letter === o.letter) r[r.length - 1].title = ', ' o.title;
else r.push({ ...o });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
let arr = [
{ letter: "A", title: "All" },
{ letter: "G", title: "Car" },
{ letter: "B", title: "Business" },
{ letter: "G", title: "Cor" },
{ letter: "A", title: "All" },
];
arr.sort((a, b) => a.letter.localeCompare(b.letter));
var result = arr.reduce((unique, o) => {
if(!unique.some(obj => obj.letter === o.letter )) {
unique.push(o);
}
return unique;
},[]);
console.log("unique and sorted arr: ", result);