sergiolenza
10/31/2018 - 3:59 PM

ES6 filtering with reduce

/**
 * Filter an array with reduce which has a better performance.
 * @param {string} query - The string we want to search.
 * @param {array} list - The array we want to filter.
 * @param {string} prop - The property we want to match.
 * @returns {array} - Filtered list
 */
const searchReducer = (query, list, prop) =>
  list.reduce((prev, curr) => {
    if (curr[prop] === query) {
      prev.push(curr);
    }
    return prev;
  }, []);
  
// arrayList = [{ name: 'Foo' }, { name: 'Bar' }];
// searchReducer('Foo', arrayList, 'name');