Javascript - sort array based on another array

后端 未结 22 1471
鱼传尺愫
鱼传尺愫 2020-11-22 03:45

Is it possible to sort and rearrange an array that looks like this:

itemsArray = [ 
    [\'Anne\', \'a\'],
    [\'Bob\', \'b\'],
    [\'Henry\', \'b\'],
             


        
22条回答
  •  醉酒成梦
    2020-11-22 04:09

    let a = ['A', 'B', 'C' ]
    
    let b = [3, 2, 1]
    
    let c = [1.0, 5.0, 2.0]
    
    // these array can be sorted by sorting order of b
    
    const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]))
    
    const sortBy = (a, b, c) => {
      const zippedArray = zip([a, b, c])
      const sortedZipped = zippedArray.sort((x, y) => x[1] - y[1])
    
      return zip(sortedZipped)
    }
    
    sortBy(a, b, c)
    

提交回复
热议问题