Skip to content

Instantly share code, notes, and snippets.

@cheapsteak
Last active August 29, 2015 14:02
Show Gist options
  • Save cheapsteak/cea2ee31b992de21a937 to your computer and use it in GitHub Desktop.
Save cheapsteak/cea2ee31b992de21a937 to your computer and use it in GitHub Desktop.
Turning a normal array into an associative array using aribitrary property

Given

var countries = [
  {
    country: "Canada",
    capital: {
      name: "Ottawa",
      population: 883391
    }
  },
  {
    country: "China",
    capital: {
      name: "Beijing",
      population: 11510000
    }
  },
  {
    country: "Australia",
    capital: {
      name: "Canberra",
      population: 358222
    }
  }
];

Increase lookup speed at the cost of looping once through the entire array by creating an index on capital name.

var countriesMappedByCapital = _(countries).indexBy(function (country) {
  return country.capital.name
});

value of countriesMappedByCapital:

{
  "Ottawa": {
    "country": "Canada",
    "capital": {
      "name": "Ottawa",
      "population": 883391
    }
  },
  "Beijing": {
    "country": "China",
    "capital": {
      "name": "Beijing",
      "population": 11510000
    }
  },
  "Canberra": {
    "country": "Australia",
    "capital": {
      "name": "Canberra",
      "population": 358222
    }
  }
}

If indexed items are not unique, items towards the end of the array will overwrite the existing mapped reference

var countries = [
  {
    country: "Israel",
    capital: {
      name: "Jerusalem",
      population: 7908000
    }
  },
  {
    country: "Palestine",
    capital: {
      name: "Jerusalem",
      population: 4047000
    }
  }
];

var countriesMappedByCapital = _(countries).indexBy(function (country) {
  return country.capital.name
});

value of countriesMappedByCapital:

{
  "Jerusalem": {
    "country": "Palestine",
    "capital": {
      "name": "Jerusalem",
      "population": 4047000
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment