greatTeacherOnizuka
greatTeacherOnizuka

Reputation: 565

Javascript - avoid multiple array.filters being called

I have a piece of code that looks like:

const desktop = platform.filter(el => el == "desktop").length;
const mobile = platform.filter(el => el == "mobile").length;
const android = platform.filter(el => el == "android").length;

and so on..

Basically I have an array that contains multiple entries of those strings and I want to collect the length of each property in a variable. The above works but I was wondering if there is a cleaner way to avoid filter through the array multiple times?

Upvotes: 0

Views: 69

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Use reduce and build one generic object.

const platforms = ['desktop', 'android', 'desktop', 'android', 'mobile'];
const len = platforms.reduce(
  (acc, item) =>
    Object.assign(acc, { [item]: item in acc ? acc[item] + 1 : 1 }),
  {}
);

console.log(len['desktop'], len.mobile)

Upvotes: 0

Scott Sauyet
Scott Sauyet

Reputation: 50807

While it would not avoid the multiple iterations, you could write an equivalent more cleanly:

const desktop = platform .includes ("desktop")
const mobile =  platform .includes ("mobile")
const android = platform .includes ("android")

But if the multiple iterations are a real problem, Ori Drori's technique should cover it.

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192287

You can use a single reduce to count the number of appearances of the items:

const platform = ['desktop', 'other', 'mobile', '', 'other', 'android', 'android'];

const { desktop, mobile, android } = platform.reduce((r, el) => {
  if (el in r) r[el]++;

  return r;
}, { desktop: 0, mobile: 0, android: 0 });

console.log({ desktop, mobile, android });

Upvotes: 4

Related Questions