-1

TL;DR: When would you personally use a JS array over a Map, despite Map being more efficient?

I have read the this question and would like to see more opinions.

The last company I worked for had its front-end React-based client fetch multiple arrays of objects from the server, (say, multiple projects). Every such project has a unique ID, and everything was managed in state-management stores, such that for example, when the user selects a project to view, the "selected project" would be implemented as follows:

class ProjectStore {
  projects: object[];
  selectedId: string;

  setSelectedId(id: string) {
    this.selectedId = id;
  }

  get selectedProject() {
    return this.projects.find(project => project.id === this.selectedId);
  }
}

This means that, every time the selected ID changes, a find operation occurs with complexity O(n) (where n is the number of projects). I found this to be quite jarring - if all projects have an ID, and we frequently need to find a project by its ID, why not instead implement using a Map, where fetching would be done in O(1)?

projects: Map<string, object>;
selectedId: string;

get selectedProject() {
  return this.projects.get(this.selectedId);
}

Just like find, this also returns either the result or undefined, so the choice to use an array over a map confounded me.

My team lead explained that, while technically more efficient, working with JS Maps is not commonplace, can be more confusing than using an array and most importantly, given the small data sizes (we're talking couple dozen objects per array at most), the extra complexity is insignificant enough so as to allow choosing the less efficient method for the sake or clarity.

My question is, what would you, the reader, do, in this case, and why? Would you use an array or a Map, and if you saw it being done one way and advocated for the other, how would you frame your reasoning for the structure change?

Ronny Efronny
  • 835
  • 5
  • 19

2 Answers2

0

As the team lead explains, either option leads to a negligible change in performance but also talks about differences in familiarity. It is possible that they prefer using plain arrays because they have considerably more experience using it and are against suddenly hopping on to Map. They also might think that in the future, developers will be more experienced using arrays than Maps and thus be able to maintain the codebase better.

I would use a Map though since it the code is much simpler and the small performance boost is a nice bonus.

Richie Bendall
  • 5,657
  • 3
  • 32
  • 49
-1

What about using a simple object in the same way as you've used a Map? Object is commonplace for JavaScript developers and complexity would be O(1).

projects: Record<string, object>;
selectedId: string;

get selectedProject() {
  return this.projects[this.selectedId];
}
Fifciuux
  • 694
  • 5
  • 7