Tags:JavaScript
Category: Front End
Common utils used in processing arrays
- given a array that contains empty || null || undefined || false elements
/**
*
* @param arr given an array
* @returns {Array} return an array that only contains values and true
*/
remove(arr) {
/*
filter(callback) use array provided to create a new array and
elements in new array must have a value or not null or true.
if(el) arr.push(el ) "" == true // false " " == true // false
*/
return arr.filter( (el) => {
return el;
});
// new solution
return arr.filter(Boolean)
- Sort an array by obj's property
// sort an array by obj's property
/**
*
* @param arr given an Object array
* @param sortBy target property used to compare two elements
* @param isDesc define the order of the array
* @returns {Array} return array after sort
*/
sortObj(arr,sortBy,isDesc) {
return arr.sort((a,b) => {
if(isDesc) {
return (typeof a[sortBy] === "string") ? a[sortBy] < b[sortBy] : b[sortBy] - a[sortBy];
}else{
return (typeof a[sortBy] === "string") ? a[sortBy] > b[sortBy] : a[sortBy] - b[sortBy];
}
});
}