Order & filter an array
Return the top 3 ids of the lowest value given a single clientId
Advanced
Instructions
Write a function that receives an input array, a clientId and a number T and returns the top T ids ordered by the lowest value for the given clientId:
Sample input data:
const input = [
{ id: 1, clientId: 12, value: 13 },
...
];
const clientId = 12;
const T = 3;
Tests
0/5
Function Call:
Expected:
topIds([{ id: 1, clientId: 12, value: 13 }, { id: 2, clientId: 12, value: 10 }, { id: 3, clientId: 12, value: 15 }], 12, 2)
[
2,
1
]
Run test
topIds([{ id: 1, clientId: 12, value: 13 }, { id: 2, clientId: 1, value: 10 }, { id: 3, clientId: 12, value: 15 }], 12, 2)
[
1,
3
]
Run test
topIds([{ id: 1, clientId: 12, value: 13 }, { id: 2, clientId: 12, value: 15 }, { id: 3, clientId: 12, value: -13 }, { id: 4, clientId: 12, value: 2 }, { id: 5, clientId: 11, value: 11 }, { id: 6, clientId: 10, value: -11 }, { id: 7, clientId: 45, value: -1 }], 12, 3)
[
3,
4,
1
]
Run test
topIds([{ id: 1, clientId: 10, value: 13 }], 12, 3)
[]
Run test
topIds([{ id: 1, clientId: 10, value: 13 }], 10, 3)
[
1
]
Run test
See Solution
Solution
Basic idea
- Filter the input array to include only items with the given clientId.
- Sort the filtered array by value in ascending order.
- Slice the sorted array to include only the top T items.
- Map the resulting array to extract the ids.
const topIds = (input, clientId, T ) => {
const result = input
.filter(item => item.clientId === clientId)
.sort((a, b) => a.value - b.value)
.slice(0, T)
.map(a => a.id)
return result
}
Algorithm Detailed Explanation
- Filter the input array to include only items with the given clientId.
- Sort the filtered array by value in ascending order.
- Slice the sorted array to include only the top T items.
- Map the resulting array to extract the ids.
Complexity Analysis
The time complexity of this solution is O(n log n) where n is the number of items in the input array. This is because the sort function has a time complexity of O(n log n). The space complexity is O(n) because we are creating a new array to store the filtered items.
Any improvement idea? Share with us!