Assuming you are developing a reading app that tracks users' reading sessions, the data is recorded in the following format:
const sessions = [
{ user: 8, duration: 50, books: ['The Hobbit'] },
{ user: 7, duration: 150, books: ['Pride and Prejudice'] },
{ user: 1, duration: 10, books: ['The Lord of the Rings'] },
{ user: 7, duration: 100, books: ['The Great Gatsby', 'Animal Farm'] },
{ user: 7, duration: 200, books: ['The Great Gatsby'] },
{ user: 2, duration: 200, books: ['1984'] },
{ user: 2, duration: 200, books: ['The Great Gatsby'] }
Each object has the following fields:
You need to implement a function called consolidateData to merge the reading data for each user according to the following rules:
duration fields.books arrays, remove duplicate titles, and sort them alphabetically.Given the example input, the expected output is:
[
{ user: 8, duration: 50, books: ['The Hobbit'] },
{ user: 7, duration: 450, books: ['Animal Farm', 'Pride and Prejudice', 'The Great Gatsby'] },
{ user: 1, duration: 10, books: ['The Lord of the Rings'] },
{ user: 2, duration: 400, books: ['1984', 'The Great Gatsby'] },
]
function consolidateData(sessions){
const userMap = new Set()
const resultArray = []
for (const session of sessions) {
const { user, duration, books } = session
if (userMap.has(user)) {
const userDataIndex = resultArray.findIndex(userData => userData.user === user)
resultArray[userDataIndex].duration += session.duration
const booksList = Array.from(new Set( [...resultArray[userDataIndex].books, ...session.books] ))
resultArray[userDataIndex].books = booksList
}else{
userMap.add(user)
resultArray.push({
user,
duration,
books
})
}
}
return resultArray
}