Middle
Live coding task: given an array of objects with fields id, title, and data — you need to get unique titles ignoring case.
sobes.tech AI
Answer from AI
To obtain unique values of the title field without considering case from an array of objects, you can use the following approach in JavaScript:
const items = [
{ id: 1, title: 'Apple', data: '...' },
{ id: 2, title: 'apple', data: '...' },
{ id: 3, title: 'Banana', data: '...' },
{ id: 4, title: 'BANANA', data: '...' },
{ id: 5, title: 'Cherry', data: '...' }
];
const uniqueTitles = [];
const seen = new Set();
for (const item of items) {
const lowerTitle = item.title.toLowerCase();
if (!seen.has(lowerTitle)) {
seen.add(lowerTitle);
uniqueTitles.push(item.title);
}
}
console.log(uniqueTitles); // ['Apple', 'Banana', 'Cherry']
Here, we use a Set to track already encountered titles in lowercase to avoid duplicates, but we keep the original case of the first encountered value.