• ARعربي
  • ENEnglish
  • ESEspañol
  • FAفارسی
  • FRFrançais
  • IDIndonesia
  • ITItaliano
  • JA日本語
  • KO한국어
  • RUРусский
  • TRTürkçe
  • UKУкраїнська
  • ZH简体中文

Nous souhaitons rendre ce projet open source disponible pour les gens du monde entier.

Aidez-nous à traduire le contenu de ce tutoriel dans votre langue!

    AcheterEPUB/PDF
    Carte du tutoriel
    Partager
    • Tutoriel
    • JavaScript le langage
    • Types de données
    • Méthodes de tableau
    retour au cours
    Ce contenu n'est disponible que dans les langues suivantes :عربي, English, Español, فارسی, Indonesia, Italiano, 日本語, Русский, Українська, 简体中文. Merci de

    Create keyed object from array

    importance: 4

    Let’s say we received an array of users in the form {id:..., name:..., age:... }.

    Create a function groupById(arr) that creates an object from it, with id as the key, and array items as values.

    For example:

    let users = [
      {id: 'john', name: "John Smith", age: 20},
      {id: 'ann', name: "Ann Smith", age: 24},
      {id: 'pete', name: "Pete Peterson", age: 31},
    ];
    
    let usersById = groupById(users);
    
    /*
    // after the call we should have:
    
    usersById = {
      john: {id: 'john', name: "John Smith", age: 20},
      ann: {id: 'ann', name: "Ann Smith", age: 24},
      pete: {id: 'pete', name: "Pete Peterson", age: 31},
    }
    */

    Such function is really handy when working with server data.

    In this task we assume that id is unique. There may be no two array items with the same id.

    Please use array .reduce method in the solution.

    Open a sandbox with tests.

    function groupById(array) {
      return array.reduce((obj, value) => {
        obj[value.id] = value;
        return obj;
      }, {})
    }

    Ouvrez la solution avec des tests dans une sandbox.

    • © 2007—2025  Ilya Kantor
    • à propos du projet
    • nous contacter