DEV Community

Discussion on: How to convert an array into a specific format in Javascript?

Collapse
peerreynders profile image
peerreynders • Edited on
const toLanguage = ({ language }) => language;
const toUser = ({ user }) => user;
const toLanguageUsers = ([language, group]) => {
  const user = group.map(toUser);
  return {
    language,
    user,
    count: user.length,
  };
};

const formattedArray = Object.entries(endorsedSkills.groupBy(toLanguage)).map(
  toLanguageUsers
);
console.log(formattedArray);
Enter fullscreen mode Exit fullscreen mode

Or the less readable version

const formattedArray = Object.entries(
  endorsedSkills.groupBy(({ language }) => language)
).map(([language, group]) => {
  const user = group.map(({ user }) => user);
  return {
    language,
    user,
    count: user.length,
  };
});
console.log(formattedArray);
Enter fullscreen mode Exit fullscreen mode

MDN: Array.prototype.groupBy()

Array Grouping Proposal

Currently at Stage 3

Currently polyfilled by core-js or perhaps something like

function groupBy(array, toKey) {
  const groupElement = (groups, element) => {
    const key = toKey(element);

    if (Object.hasOwn(groups, key)) groups[key].push(element);
    else groups[key] = [element];

    return groups;
  };

  return array.reduce(groupElement, {});
}

const toLanguage = ({ language }) => language;
const toUser = ({ user }) => user;
const toLanguageUsers = ([language, group]) => {
  const user = group.map(toUser);
  return {
    language,
    user,
    count: user.length,
  };
};

const formattedArray = Object.entries(groupBy(endorsedSkills, toLanguage)).map(
  toLanguageUsers
);
console.log(formattedArray);
Enter fullscreen mode Exit fullscreen mode

to be replaced later.

Collapse
iainsimmons profile image
Iain Simmons

I'm looking forward to this one being better supported!