0

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?

0

3 Answers 3

4

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 });

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.