Reputation: 2714
I'm searching for a nice approach for the following task: I have a game with rounds. In each round we have a number between 1-10.
This is how I'm doing it so far but I'm stuck.
gameValues.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
I want to count the double entrees in my array but I only want to watch out for the last 5 rounds.
Round 6 ( We already have 5 values ):
gameValues = [9,9,9,2,1]
result: 9:3, 2:1, 1:1,
Round 7 ( Now we have 6 values but I only want to count the first 5):
gameValues = [3,9,9,9,2,1]
result: 3:1, 9:3, 2:1,
I can't manage to only count the last 5 rounds..
Upvotes: 1
Views: 74
Reputation: 25398
You can get the last 5 numbers in an array using splice and then using reduce you can get the counts of each number.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice().
function countLastFive(arr) {
return arr.splice(-5).reduce((acc, curr) => {
acc[curr] = acc[curr] ? ++acc[curr] : 1;
return acc;
}, {});
}
console.log(countLastFive([9, 9, 9, 2, 1, 3, 1]));
console.log(countLastFive([9, 9, 9, 2, 1]));
console.log(countLastFive([3, 9, 9, 9, 2, 6, 4, 3, 2, 1]));
Just be sure that the slice changes the original array. So it would be better to clone the array so that It won't change the original array
function countLastFive(arr) {
return arr.splice(-5).reduce((acc, curr) => {
acc[curr] = acc[curr] ? ++acc[curr] : 1;
return acc;
}, {});
}
const arr1 = [9, 9, 1, 9, 2, 1];
const arr2 = [9, 9, 1, 9, 2, 1];
console.log("Before -> arr1 => ", arr1);
console.log(countLastFive(arr1));
console.log("After -> arr1 => ", arr1);
console.log("Before -> arr2 => ", arr2);
console.log(countLastFive([...arr2]));
console.log("After -> arr2 => ", arr2);
Upvotes: 2
Reputation: 6746
const gameValues = [3,9,9,9,2,1]
const uniq = gameValues.splice(-5)
.map((number) => {
return {
count: 1,
number: number
}})
.reduce((a, b) => {
a[b.number] = (a[b.number] || 0) + b.count
return a
}, {})
console.log(uniq);
Upvotes: 2
Reputation: 817
Use gameValues.slice(-5)
to get the last 5 values of the array, then do the same count operation :
gameValues = [3,9,9,9,2,1]
counts = {}
gameValues.slice(-5).forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
console.log(counts);
// { '1': 1, '2': 1, '9': 3 }
Upvotes: 3