Last active
March 12, 2018 14:17
-
-
Save tnguven/3056c3e7bd5d394e1c6db83f5bc1ea44 to your computer and use it in GitHub Desktop.
Array of object manipulation example
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
function filterByLetters(options, filter) { | |
if (filter) { | |
let data = [...options]; | |
let restData = [...options]; | |
const filterIsNum = parseInt(filter); | |
let result = []; | |
// filter with number | |
if (filterIsNum) { | |
const filtered = data | |
.filter((item) => { | |
return isMatch({ | |
str: getNumber(item.label), | |
filter, | |
num: true, | |
hasMatch: true | |
}); | |
}) | |
.sort( | |
(a, b) => parseInt(getNumber(a.label)) - parseInt(getNumber(b.label)) | |
); | |
const restOfList = restData.filter((item) => { | |
return isMatch({ str: getNumber(item.label), filter, num: true }); | |
}); | |
result = [...filtered, ...restOfList]; | |
} else { | |
// filter with letter | |
const filtered = data.filter((item) => | |
isMatch({ | |
str: item.label, | |
filter, | |
hasMatch: true | |
}) | |
); | |
const restOfList = restData.filter((item) => { | |
return isMatch({ str: item.label, filter }); | |
}); | |
result = [...filtered, ...restOfList]; | |
} | |
return result; | |
} | |
// Do no filtering, just return all options | |
return options; | |
} | |
function isMatch({ str, filter, num = false, hasMatch } = {}) { | |
let result = true; | |
for (let i = 0; i < filter.length; i++) { | |
const src = num ? str[i] : str[i].toUpperCase(); | |
const filt = num ? filter[i] : filter[i].toUpperCase(); | |
if (hasMatch) { | |
if (src !== filt) result = false; | |
} else { | |
if (src === filt) result = false; | |
} | |
} | |
return result; | |
} | |
function getNumber(str) { | |
return str.split('+')[1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment