1

I have an array of objects

Using a for loop i am re-ordering my array of objects based on the property phoneType's value. Since this is a data response from an api, i am saying always place the phone number that has a phoneType of Primary first in my return arrary.

Question for you...I am not sure if this is the best way to do this. Is there a different way to accomplish this? I was thinking about using Object.Keys to do this, but could not figure it out.

Here is my loop:

export function examplefunctionForStackOverflow(phoneNumbers) {
  const phoneNumberArray = [];

  if (typeof phoneNumbers !== 'undefined') {
    for (const i in phoneNumbers) {

      const number = phoneNumbers[i].number;
      const phoneType = phoneNumbers[i].phoneType;

      phoneNumbers[i].phoneType === "Primary" ?
        phoneNumberArray.unshift({
          key: phoneType,
          value: number
        }) :
        phoneNumberArray.push({
          key: phoneType,
          value: number
        });
    }
  }
  return phoneNumberArray;
}


   data: {
    phoneNumbers: [{
      number: "(999) 999-9999",
      extension: "",
      phoneType: "CELL"
    },
    {
      number: "(888) 888-8888",
      extension: "",
      phoneType: "Primary"
    },
    {
      number: "(777) 777-7777",
      extension: "777",
      phoneType: "WORK"
    }
    ]
  • Here is the code you COULD have posted in a [mcve] using the `<>` snippet editor https://jsfiddle.net/hc447rog/ – mplungjan Jul 03 '17 at 14:15

1 Answers1

2

You can simply sort the array:

let data = {
  phoneNumbers: [{
      number: "(999) 999-9999",
      extension: "",
      phoneType: "CELL"
    },
    {
      number: "(888) 888-8888",
      extension: "",
      phoneType: "Primary"
    },
    {
      number: "(777) 777-7777",
      extension: "777",
      phoneType: "WORK"
    }
  ]
};

data.phoneNumbers.sort((a, b) => {
  if (a.phoneType === 'Primary') return -1;
  return 1;
});

console.log(data.phoneNumbers);
baao
  • 71,625
  • 17
  • 143
  • 203