Skip to content

Instantly share code, notes, and snippets.

@blackfry
Last active February 26, 2019 05:12
Show Gist options
  • Save blackfry/8fa0653bde5649b679fbe5f64caecf63 to your computer and use it in GitHub Desktop.
Save blackfry/8fa0653bde5649b679fbe5f64caecf63 to your computer and use it in GitHub Desktop.
JS filter elements
/**
https://www.hackerrank.com/challenges/filter-elements/problem
------
Given a list of N integers A = [a1, a2, ..., aN], you have to
find those integers which are repeated at least K times.
In case no such element exists you have to print -1.
If there are multiple elements in A which are repeated at least K times,
then print these elements ordered by their first occurrence in the list.
*/
const filterFn = (nums, k) => {
const result = nums.reduce((acc, num, index) => {
const numInArray = nums.filter(n => n === num);
if (!acc[num] && numInArray.length >= k) {
acc[num] = { count: numInArray.length, index };
}
return acc;
}, {});
const entries = Object.entries(result);
return entries.length === 0
? '-1'
: entries
.sort((a, b) => a[1].index - b[1].index)
.map(x => x[0])
.join(' ');
};
const nums = [4, 5, 2, 5, 4, 3, 1, 3, 4];
let k = 2;
filterFn(nums, k);
// "4 5 3"
k = 3;
filterFn(nums, k);
// "-1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment