从现有阵列创建新结果 [英] Create a new result from an existing array

查看:50
本文介绍了从现有阵列创建新结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像这样的样本数据,我需要从结果数组中获取finalResult数组:

If I have a sample data that looks like this I need to get finalResult array from result array:

let result = [{
    type: ['Science'],
    link: "www.educatorsector.com"
  },
  {
    type: ['Sports', 'News'],
    link: "www.skysports-news.com"
  },
  {
    type: ['Sports', 'Science'],
    link: "www.cnn-news.com"
  }];

finalResult = [
{ type : "Science", numberOfLinks : 2 }, 
{ type : "Sports", numberOfLinks : 2 },
{ type : "News", numberOfLinks : 1 }]

orThisFinalResult = [
{ type : "Science", links : ["www.educatorsector.com", "www.cnn-news.com"],
{ type : "Sports", links : ["www.skysports-news.com", "www.cnn-news.com"],
{ type : "News", links : ["www.skysports-news.com"]
 }

推荐答案

使用 Array.flatMap()获取类型数组.将类型数组简化为计数图.将Map转换为条目数组,然后将其映射到对象数组:

Use Array.flatMap() to get an array of types. Reduce the array of types to a Map of counts. Convert the Map to an array of entries, and then map it to an array of objects:

const result = [{"type":["Science","Business"],"link":"www.educatorsector.com"},{"type":["Sports","News"],"link":"www.skysports-news.com"},{"type":["Sports","Health","Science"],"link":"www.cnn-news.com"},{"type":["Health"],"link":"www.healthsector.com"}];

const counts = Array.from(
    result
      .flatMap(o => o.type) // flatten to array of types
      .reduce((acc, type) => // create a Map of counts
        acc.set(type, (acc.get(type) || 0) + 1), 
      new Map)
  )
  .map(([type, numberOfLinks]) => ({ type, numberOfLinks })); // convert the Map's entries to an array of objects

console.log(counts);

这篇关于从现有阵列创建新结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆