Skip to content

Instantly share code, notes, and snippets.

@ninadvadujkar
Last active January 3, 2022 12:27
Show Gist options
  • Save ninadvadujkar/76845111b4e534282c031e2629eed8fe to your computer and use it in GitHub Desktop.
Save ninadvadujkar/76845111b4e534282c031e2629eed8fe to your computer and use it in GitHub Desktop.
Basic usage of Array.reduce
// Basic usage of reduce to find sum of numbers in an array
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((prev, curr) => prev + curr, 0);
console.log('sum', sum);
// Basic usage of reduce to convert an array of objects into an object.
// For e.g.
// Input -> [{ id: 1, key: 'a', value: 'a' }, { id: 2, key: 'b', value: 'b' }, { id: 3, key: 'c', value: 'c' }];
// Output -> { 1: { key: 'a', value: 'a' }, 2: { key: 'b', value: 'b' }, 3: { key: 'c', value: 'c' } };
// Now you might ask, what's the use of this and where we might use this?
// Imagine this usecase:
// This was a huge array and time complexity is important for us.
// We have to find the key/value pairs multiple times based on `id`.
// We have memory to spare but not CPU cycles.
// Once it's an object, searching a certain object by `id` takes just O(1) time as opposed to O(n) when it's an array (no need to use Array.find/Array.filter etc.)
// Just `output[id]` is sufficient.
// In this case, time complexity of reduce is also O(n) but we do that just once and then finding any key/value by `id` is going to take constant time even if we have to find it 100x times.
const input = [{
id: 1,
key: 'a',
value: 'a'
},
{
id: 2,
key: 'b',
value: 'b'
},
{
id: 3,
key: 'c',
value: 'c'
}];
const output = input.reduce((prev, curr) => ({
...prev,
[curr.id]: {
key: curr.key,
value: curr.value
}
}), {});
console.log('output', output);
console.log('find by id=2 (array)', input.find(i => i.id === 2)); // O(n) 🐢
console.log('find by id=2 (object)', output['2']); // O(1) 🔥
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment