【问题标题】:Use reduce and add another value to the result object使用 reduce 并向结果对象添加另一个值
【发布时间】:2021-06-30 09:27:20
【问题描述】:

books 数组中的对象示例:

const books = [
  {
    id: "5f447132d487bd81da01e25e",
    title: "sit eiusmod occaecat eu magna",
    genre: "Science",
    authorId: 8,
    borrows: [
      {
        id: "5f446f2e2cfa3e1d234679b9",
        returned: false,
      },
      {
        id: "5f446f2ed3609b719568a415",
        returned: true,
      },
      {
        id: "5f446f2e1c71888e2233621e",
        returned: true,
      },
      {
        id: "5f446f2e6059326d9feb9a68",
        returned: true,
      },
      {
        id: "5f446f2ede05a0b1e3394d8b",
        returned: true,
      },
      {
        id: "5f446f2e4081699cdc6a2735",
        returned: true,
      },
      {
        id: "5f446f2e3900dfec59489477",
        returned: true,
      },
      {
        id: "5f446f2e6059326d9feb9a68",
        returned: true,
      },
      {
        id: "5f446f2e409f8883af2955dd",
        returned: true,
      },
      {
        id: "5f446f2e3900dfec59489477",
        returned: true,
      },
      {
        id: "5f446f2eae901a82e0259947",
        returned: true,
      },
      {
        id: "5f446f2ef2ab5f5a9f60c4f2",
        returned: true,
      },
      {
        id: "5f446f2ea6b68cf6f85f6e28",
        returned: true,
      },
      {
        id: "5f446f2eed18105706d6ca19",
        returned: true,
      },
      {
        id: "5f446f2eae901a82e0259947",
        returned: true,
      },
      {
        id: "5f446f2e91c2af00cb74e82b",
        returned: true,
      },
      {
        id: "5f446f2e5aa2bb5545a0f8a6",
        returned: true,
      },
      {
        id: "5f446f2ea508b6a99c3e42c6",
        returned: true,
      },
      {
        id: "5f446f2e50cc2da9cd80efdb",
        returned: true,
      },
      {
        id: "5f446f2e0b3e2ff72fc503e7",
        returned: true,
      },
      {
        id: "5f446f2e91c2af00cb74e82b",
        returned: true,
      },
      {
        id: "5f446f2ef795e593cd3cd19d",
        returned: true,
      },
      {
        id: "5f446f2e2f35653fa80bf490",
        returned: true,
      },
      {
        id: "5f446f2e7b9cd304fed3a8bc",
        returned: true,
      },
      {
        id: "5f446f2ed9aac23c0340aab2",
        returned: true,
      },
    ],
  },

我需要我的函数 getMostCommonGenres(books) 来:返回一个数组,其中包含五个或更少的对象,这些对象代表最常见的流派,从最常见到最少的顺序排列,如下所示:(如果存在超过五本书,则只有顶部五个应该返回。)

getMostCommonGenres(books);
  [
    { name: "Nonfiction", count: 9 },
    { name: "Historical Fiction", count: 7 },
    { name: "Thriller", count: 7 },
    ...
  ]

这是我目前所拥有的:

function getMostCommonGenres(books) {
  const genreArray = books.reduce((acc, book) => {
    acc[book.name] = book.genre;
    return acc;
  }, {});
}

我很确定我已经得到了我需要的一切,除了流派之后的“计数”值。我不确定如何将它添加到对象中。我也不确定如何阻止前五名的计数。我刚刚完成了课程中的高级功能部分,所以我应该使用 forEach、find、filter、some、every、reduce 或 sort。我也不允许使用单字母变量。提前感谢您的任何帮助。

【问题讨论】:

    标签: javascript arrays function javascript-objects


    【解决方案1】:

    我得到的答案似乎没有用,但这对我有用:

    function getMostCommonGenres(books) {
      const bookGenres = books.map((book) => book.genre);
      const temp = [];
      //map over book genres
      bookGenres.map((genre) => {
        //for each genre, first check to see if genre already exists in array
        const genreLocation = temp.findIndex((element) => element.name === genre);
        //second, if it exists, increase count by 1
        if (genreLocation >= 0) {
          temp[genreLocation].count = temp[genreLocation].count + 1;
          //else, if it don't exist, push a new genre object onto array with count of 1
        } else {
          temp.push({ name: genre, count: 1 });
        }
      });
      temp.sort((a, b) => b.count - a.count);
      if (temp.length > 5) {
        return temp.slice(0, 5);
      }
      return temp;
    }
    

    【讨论】:

      【解决方案2】:

      这是我创建的用于对您的图书类型进行排序的代码:

      function getMostCommonGenres(books) {
          returnStrs = [];
          genres = []; // [["genreName1", 1],["genreName2",1]] The number is the count
          var i;
          for (i = 0; i < books.length; i++) {
              genre = books[i].genre;
              if (!DoesGenreExist(genre, genres)) {
                  genres.push([genre, 1]);
              }
          }
          genres.sort(function (a, b) { // Sort genres by the count
              return b[1] - a[1];
          });
      
          numGenres = genres.length
          if (numGenres > 5) { // take 5 max
              numGenres = 5
          }
      
          for (i = 0; i < numGenres; i++) {
              var summary = new GenreSummary(genres[i][0], genres[i][1])
              returnStrs.push(JSON.stringify(summary)); // Create genre string and add to return value
          }
          console.log(returnStrs)
          return returnStrs;
      }
      
      function DoesGenreExist(genreStr, genres) { // If it exists it also increments the count
          for (i = 0; i < genres.length; i++) {
              if (genres[i][0] == genreStr) {
                  genres[i][1]++;
                  return true;
              }
          }
          return false;
      }
      
      class GenreSummary {
          constructor(name, count) {
              this.name = name;
              this.count = count;
          }
      }
      

      我从你的第一个代码 sn-p 输入你的书并得到以下输出:

      [ '{"name":"Science","count":1}' ]
      

      【讨论】:

      • 此代码有效,但我不熟悉新的、您对 JSON 文件或类的使用。我也不允许使用单字符变量,但我没有在原帖中提到这一点。不过感谢您的回复!
      【解决方案3】:

      您可以使用 reduce 和 slice 轻松实现此目的(获得 5 个元素)

      const books = [{
        id: "5f447132d487bd81da01e25e",
        title: "sit eiusmod occaecat eu magna",
        genre: "Science",
        authorId: 8,
        borrows: [{
            id: "5f446f2e2cfa3e1d234679b9",
            returned: false,
          },
          {
            id: "5f446f2ed3609b719568a415",
            returned: true,
          },
          {
            id: "5f446f2e1c71888e2233621e",
            returned: true,
          },
          {
            id: "5f446f2e6059326d9feb9a68",
            returned: true,
          },
          {
            id: "5f446f2ede05a0b1e3394d8b",
            returned: true,
          },
          {
            id: "5f446f2e4081699cdc6a2735",
            returned: true,
          },
          {
            id: "5f446f2e3900dfec59489477",
            returned: true,
          },
          {
            id: "5f446f2e6059326d9feb9a68",
            returned: true,
          },
          {
            id: "5f446f2e409f8883af2955dd",
            returned: true,
          },
          {
            id: "5f446f2e3900dfec59489477",
            returned: true,
          },
          {
            id: "5f446f2eae901a82e0259947",
            returned: true,
          },
          {
            id: "5f446f2ef2ab5f5a9f60c4f2",
            returned: true,
          },
          {
            id: "5f446f2ea6b68cf6f85f6e28",
            returned: true,
          },
          {
            id: "5f446f2eed18105706d6ca19",
            returned: true,
          },
          {
            id: "5f446f2eae901a82e0259947",
            returned: true,
          },
          {
            id: "5f446f2e91c2af00cb74e82b",
            returned: true,
          },
          {
            id: "5f446f2e5aa2bb5545a0f8a6",
            returned: true,
          },
          {
            id: "5f446f2ea508b6a99c3e42c6",
            returned: true,
          },
          {
            id: "5f446f2e50cc2da9cd80efdb",
            returned: true,
          },
          {
            id: "5f446f2e0b3e2ff72fc503e7",
            returned: true,
          },
          {
            id: "5f446f2e91c2af00cb74e82b",
            returned: true,
          },
          {
            id: "5f446f2ef795e593cd3cd19d",
            returned: true,
          },
          {
            id: "5f446f2e2f35653fa80bf490",
            returned: true,
          },
          {
            id: "5f446f2e7b9cd304fed3a8bc",
            returned: true,
          },
          {
            id: "5f446f2ed9aac23c0340aab2",
            returned: true,
          },
        ],
      }, ];
      
      function getMostCommonGenres(books) {
        const result = books.reduce((acc, book) => {
          if (book.borrows.length > 5) {
            acc.push({
              name: book.genre,
              count: book.borrows.length,
            });
          }
          return acc;
        }, []);
        return result.sort((a, b) => b.count - a.count)
                     .slice(0, 5);
      }
      
      const resultArray = getMostCommonGenres(books);
      console.log(resultArray);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-04
        • 2021-08-26
        • 1970-01-01
        • 2011-02-08
        • 2021-10-10
        • 2021-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多