【问题标题】:Issue when trying to sort array?尝试对数组进行排序时出现问题?
【发布时间】:2021-12-17 11:53:32
【问题描述】:
        // const first = data.groups_with_selected[7];
        // const second = data.groups_with_selected[20];
        // data.groups_with_selected.splice(2, 0, first, second);
        // data.groups_with_selected.splice(9, 1)
        // data.groups_with_selected.splice(21, 1)

但上述代码的问题在于,我能够在控制台中获取更新后的 sorted console 值。但过滤明智的是它没有更新。

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    解决这个问题的方法是先对数组进行分组,然后使用flat()对其进行展平/恢复使其具有相同的级别:

    const orderMap = ['third', 'second', 'first'];
    
    const array = [{name: 'first'}, {name: 'second'}, {name: 'third'}, {name: 'second'}];
    
    const sorted = orderMap.reduce((prev, curr, index) => {
    prev[index] = array.filter(item => item.name === curr)
    return prev
    }, []).flat()
    
    console.log(sorted)

    【讨论】:

    • 谢谢,如果可能的话,您能否说明如何在我的 api 响应中使用相同的东西。就像我如何先按名称对数组进行分组。
    • 我认为 flat() 需要在这里,因为更改后我希望它是标准的,所以...
    • 首先,orderMap 应该是正确的,我建议你 orderMap 也是从 api 提供的。那么你可以在 vue 中使用computed 来计算排序后的输出
    • 谢谢。 const orderMap = ['第三','第二','第一'];常量数组 = [{name: 'first'}, {name: 'second'}, {name: 'third'}];在我的代码的这两行中,我如何获取 orderMap ,数组(基于我的示例请给出一些想法)
    • 我收到了来自 data.groups_with_selected 的响应(后面是 for [7].name)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2021-03-28
    相关资源
    最近更新 更多