Last active
October 31, 2019 07:19
-
-
Save kingisaac95/b9db6e5f636bfffb680ff495086a4915 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sampleOptions = [ | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '100336' }, | |
{ id: 'option-type', value: '100354' }, | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '109538' }, | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '8303' }, | |
{ id: 'option-type', value: '504' }, | |
{ id: 'option-type', value: '503' }, | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '501' }, | |
]; | |
const filterUniqueOptions = (array) => { | |
// create a map to hold already stored items | |
const map = new Map(); | |
return array.reduce((result, current) => { | |
// replace 'current.value' with the key you're filtering with | |
// eg. current.myFilterKey | |
if (!map.has(current.value)) { | |
// if item is not already in map, add item to map | |
map.set(current.value, true); | |
// push new item to accumulator array | |
result.push({...curent}); | |
} | |
return result; | |
}, []); | |
}; | |
filterUniqueOptions(sampleOptions); | |
// test: jest | |
const sampleOptions = [ | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '100336' }, | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '109538' }, | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '504' }, | |
{ id: 'option-type', value: '3' }, | |
]; | |
const sampleResult = [ | |
{ id: 'option-type', value: '3' }, | |
{ id: 'option-type', value: '100336' }, | |
{ id: 'option-type', value: '109538' }, | |
{ id: 'option-type', value: '504' }, | |
]; | |
describe('Filter Unique Options', () => { | |
describe('filterUniqueOptions', () => { | |
it('should return unique array', () => { | |
const result = filterUniqueOptions(sampleOptions); | |
expect(result).toEqual(sampleResult); | |
}); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment