Search code examples
javascriptarraysecmascript-6lodash

How can I refine this JS array search function?


I have the following function:

export const functionName = (key) => {
  const data = [
    {
      displayOrder: 0,
      key: 'key-name-1',
    },
    {
      displayOrder: 2,
      key: 'key-name-2',
    },
  ];

  for (let index in data) {
    return data[index].displayOrder === 0
      ? data[index].key
      : data[0].key;
  }
};

The purpose of the function is to return the key with the lowest displayOrder. This works, but is there a better more slick method to achieve this?

Secondly, how best could I create a similar version to re-order the entire array based on displayOrder?


Solution

  • The proper method to use when you want to extract a single thing from an array (and you can't identify the element by itself with .find) is to use .reduce:

    const functionName = () => {
      const data = [
        {
          displayOrder: 0,
          key: 'key-name-1',
        },
        {
          displayOrder: 2,
          key: 'key-name-2',
        },
      ];
      const lowestDisplayObj = data.reduce((lowestObjSoFar, currentObj) => {
        if (currentObj.displayOrder < lowestObjSoFar.displayOrder) return currentObj;
        return lowestObjSoFar;
      }, { displayOrder: Infinity, key: null });
      return lowestDisplayObj.key;
    };
    console.log(functionName());

    Note that your current argument to functionName, key, was unused in your snippet, I'm not sure what it's for.

    You could also use .sort() and select the first element in the array, but that's more computationally expensive than it needs to be.