javascriptintermediate10 minutes
Predict the Output: Nested Array and Object Manipulation in JavaScript
Analyze the given JavaScript code that involves nested arrays and objects with multiple transformations. Predict what the final output will be after all operations are executed.
Challenge prompt
Examine the following JavaScript function. It takes an array of user objects, performs nested array filtering, mapping and object property updates. Predict the exact output of the function when called with the provided sample data.
Guidance
- • Follow each step of the array transformations carefully, watching for side effects on objects.
- • Track filter and map operations distinctly and note how they change the array length or values.
- • Remember that objects are passed by reference, so modifying user objects inside map affects the final result.
Hints
- • Pay attention to the filter condition on user.scores and which users are included.
- • Notice how the map function updates the age property and how that affects the output.
- • Remember the difference between shallow copying and mutating objects when working with arrays.
Starter code
function processUsers(users) {
return users
.filter(user => user.scores.some(score => score > 80))
.map(user => {
user.age += 1;
user.scores = user.scores.filter(score => score > 50);
return user;
});
}
const users = [
{ name: 'Alice', age: 30, scores: [45, 82, 77] },
{ name: 'Bob', age: 25, scores: [55, 49, 68] },
{ name: 'Charlie', age: 35, scores: [95, 92, 88] },
{ name: 'Diana', age: 20, scores: [40, 42, 47] }
];
console.log(processUsers(users));Expected output
[ { name: 'Alice', age: 31, scores: [82, 77] }, { name: 'Bob', age: 26, scores: [55, 68] }, { name: 'Charlie', age: 36, scores: [95, 92, 88] } ]
Core concepts
array filterarray mapobject mutationnested array manipulation
Challenge a Friend
Send this duel to someone else and see if they can solve it.