【问题标题】:How can I sort through an Axios response?如何对 Axios 响应进行排序?
【发布时间】:2021-01-19 01:36:18
【问题描述】:

我正在使用 Axios 执行对公共 API 的 GET 请求,如果名称相同,我需要组合名称并将值添加到仅显示前 20 个(这是一个大数据集)基于最高最低金额(升序)。

Axios 响应

 [
    {
        name: "foo1",
        value: "8123.30"
    }, 
    
    {
        name: "foo1",
        value: "2852.13"
        
    }, 
    
    {
        name: "foo2",
        value: "5132.23"
    },
   
    {
        name: "foo1",
        value: "1224.20"
       
    }, 

     {
        name: "foo2",
        value: "1285.23"
        
    }
   1200...
];

预期输出

[
  {   name: "foo1",
      value: "12199.63" // from all combined "foo1" amounts in the dataset
  },

  {
     name: "foo2",
     value: "6417.46"  // from all combined "foo2" amounts in the dataset
  },
    18..
]

我试图做这样的事情......

const fetchData = () => {
    return axios.get(url)
    .then((response) => response.data)
};

function onlyWhatINeed() {
  const newArr = []
  return fetchData().then(data => {
    const sortedData = data.sort((a, b) => parseFloat(a.value) - parseFloat(b.value)); 
    // I need to loop through the dataset and add all the "values" up
   // returning only the top 20 highest values in an array of those objects 
    newArr.push(sortedData)
  })
}

但我很困惑如何将这些数据推送到排序数据的新数组(按升序排列的前 20 个值)并在我的 Web 应用程序中使用这些数据。我对创建 REST API 有点陌生,所以如果您能提供文章和/或资源,以便我能多了解一点,那将是一个很棒的奖励!

【问题讨论】:

  • 这个数据集有多大(有多少条目)?
  • axios 返回 1220 个对象

标签: javascript node.js sorting data-structures axios


【解决方案1】:

您可以使用地图组合具有相同名称的条目,然后对地图进行排序并保留前二十个元素:

function onlyWhatINeed() {
  const newArr = []
  return fetchData().then(data => {
    let map = new Map();
    data.forEach(d => {
      if(!map.has(d.name)) {
        map.set(d.name, parseFloat(d.value));
      } else {
        map.set(d.name, map.get(d.name) + parseFloat(d.value));
      }
    })
  
    return Array.from(map.entries()).sort((a, b) => a.value - b.value).slice(0, 20);

  })
}

由于您要处理大型数据集,我建议您处理此服务器端,而不是将排序任务交给客户端。

【讨论】:

    【解决方案2】:
    async function fetchData(){
        const { data } = await axios.get(url);
        let newArr = []
        data.forEach((e,i) => {
            let index = newArr.findIndex(el => el.name === e.name);
            if(index !== -1 ) newArr[index].value += parseFloat(e.value); //add to the value if an element is not unique
            if(index === -1 ) newArr.push({...e, value: parseFloat(e.value)}); //push to the array if the element is unique and convert value to float
        });
        return newArr.sort((a,b) => a.value - b.value).slice(0,20);//returns an array of 20 elements after sorting
    }
    

    请对如何使用数组和对象进行更多研究。

    【讨论】:

      【解决方案3】:

      如果您碰巧已经在使用lodash,那么这里有一个使用 lodash 链接的函数式解决方案。可能不是最佳性能,但可能对相对较小的数据集有用。

      const _ = require('lodash');
      
      const data =  [
        {
          name: "foo1",
          value: "8123.30"
        },
        {
          name: "foo1",
          value: "2852.13"
        },
        {
          name: "foo2",
          value: "5132.23"
        },
        {
          name: "foo1",
          value: "1224.20"
        },
        {
          name: "foo2",
          value: "1285.23"
        },
        {
          name: "foo3",
          value: "1000.00"
        },
        {
          name: "foo3",
          value: "2000.00"
        }
      ];
       
      // 1. convert string values to floats
      // 2. group by name
      // 3. sum values by name
      // 4. sort by descending value
      // 5. take top 20
      const output =
        _(data)
          .map(obj => ({
            name: obj.name,
            value: parseFloat(obj.value)
          }))
          .groupBy('name')
          .map((objs, key) => ({
            name: key,
            value: _.sumBy(objs, 'value')
          }))
          .orderBy(['value'], 'desc')
          .slice(0, 20)
          .value();
      
      console.log('output:', output);
      

      【讨论】:

        猜你喜欢
        • 2012-05-16
        • 1970-01-01
        • 1970-01-01
        • 2018-07-05
        • 2016-03-06
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        相关资源
        最近更新 更多