【问题标题】:Sort object of arrays by included array with lodash, and find index array使用 lodash 按包含数组对数组对象进行排序,并找到索引数组
【发布时间】:2019-04-17 14:33:49
【问题描述】:

我有一个数组对象,一个

a.b = [1,4,3]
a.c = ["a","b","c"]

我需要按“b”的相反顺序对a进行排序,这样新对象就会是

d.b = [4,3,1]
d.c = ["b","c","a"]

我还需要排序产生的索引数组:

i = [1,2,0]

请建议使用 lodash,谢谢。 哦

【问题讨论】:

    标签: sorting object indexing lodash


    【解决方案1】:

    您可以使用Schwartzian transform 将当前索引和来自b 的数值添加到使用_.map() 的[value, index] 元组数组中,使用_.orderBy() 根据值(0 index),然后再次提取带有_.map()的原始索引(1个索引)。现在您可以根据索引数组映射bc(其他属性),并返回新的排序对象。

    // order an array by an array of indexes
    const mapByIndex = (arr, indexes) => _.map(arr, (_, idx) => arr[indexes[idx]])
    
    const fn = (sortKey, o) => {
      const i = _(o[sortKey])
        .map((n, i) => [n, i]) // store the current index in tuples
        .orderBy('0') // sort the tuples by the number from b
        .map('1') // extract the original index
        .value()
    
      return _.assign({ i }, _.mapValues(o, v => 
        _.isArray(v) ? mapByIndex(v, i) : v
      ))
    }
    
    const obj = {
      b: [1,4,3],
      c: ["a","b","c"]
    }
    
    const result = fn('b', obj)
    
    const i = result.i
    
    const d = _.omit(result, 'i')
    
    console.log(d)
    
    console.log(i)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

    【讨论】:

    • 太好了,谢谢。那么如何修改 return 语句,使 result 实际上是一个像 obj 的对象,result.b = [4,3,1] 和 result.c =["b","c","a"] ?谢谢你。 O
    • 函数的返回值是一个对象,带有{ b: [], c: [], i: [] }。运行代码sn -p
    • 我做到了。这是非常优雅的。我的问题是我需要用对象d生成/替换对象a,比如d.b = [4,3,1],和d.c =["b","c","a"],所以很自然有 d 作为输出/返回而不是它的键。另一个问题是 i 不是数组(这是我需要的)。我试图让我切换到一个数组,但没有成功。如果您可以将 i 作为索引数组输出,并将 fn 作为对象 d 返回,我将不胜感激,如上所述。我挑剔的原因是我需要在coffeescript中翻译和修改上面的代码,并且按照指定的方式获取i和d将有助于我的情况。谢谢你。 O
    • Result 是一个包含原始对象数据和i 数组的对象。你从结果中提取它。函数需要以组合的方式返回它们,因为函数只能返回单个值。
    【解决方案2】:

    以下是 Ori Drori 对 coffeescript 的优雅解决方案的适度翻译(如果成功的话):

    a = {}
    a.b = [1, 4, 3]
    a.c = [ "a", "b", "c"]
    
    mapByIndex = (arr, indexes) -> _.map(arr, (_, idx) -> arr[indexes[idx]])
    i = _.map(a.b, fct = (n, i) -> [n, i])
    i = _.sortBy(i,"0")
    i = _.map(i, "1")
    i = i.reverse()
    i = _.mapValues(a, fct = (v) -> if _.isArray(v) then mapByIndex(v, i) else v)
    
    debug _.keys(i)    # b,c
    debug _.values(i)    # 4,3,1,b,c,a
    debug i.b    # 4,3,1
    debug i.c    # b,c,a
    

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      相关资源
      最近更新 更多