jeudi 30 mars 2017

sorting objects with multiple conditions

I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}

Aucun commentaire:

Enregistrer un commentaire