Javascript - sort array based on another array

后端 未结 22 1467
鱼传尺愫
鱼传尺愫 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:02

    This is what I was looking for and I did for sorting an Array of Arrays based on another Array:

    It's On^3 and might not be the best practice(ES6)

    function sortArray(arr, arr1){
          return arr.map(item => {
            let a = [];
            for(let i=0; i< arr1.length; i++){
              for (const el of item) {
                if(el == arr1[i]){
                  a.push(el);
                }   
                }
              }
              return a;
          });
        }
        
        const arr1 = ['fname', 'city', 'name'];
      const arr = [['fname', 'city', 'name'],
      ['fname', 'city', 'name', 'name', 'city','fname']];
      console.log(sortArray(arr,arr1));
    It might help someone

    0 讨论(0)
  • 2020-11-22 04:02

    Use intersection of two arrays.

    Ex:

    var sortArray = ['a', 'b', 'c',  'd', 'e'];
    
    var arrayToBeSort = ['z', 's', 'b',  'e', 'a'];
    
    _.intersection(sortArray, arrayToBeSort) 
    

    => ['a', 'b', 'e']

    if 'z and 's' are out of range of first array, append it at the end of result

    0 讨论(0)
  • 2020-11-22 04:04

    You can do something like this:

    function getSorted(itemsArray , sortingArr ) {
      var result = [];
      for(var i=0; i<arr.length; i++) {
        result[i] = arr[sortArr[i]];
      }
      return result;
    }
    

    You can test it out here.

    Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.

    refer link

    refer

    0 讨论(0)
  • 2020-11-22 04:05

    I had to do this for a JSON payload I receive from an API, but it wasn't in the order I wanted it.

    Array to be the reference array, the one you want the second array sorted by:

    var columns = [
        {last_name: "last_name"},
        {first_name: "first_name"},
        {book_description: "book_description"},
        {book_id: "book_id"},
        {book_number: "book_number"},
        {due_date: "due_date"},
        {loaned_out: "loaned_out"}
    ];
    

    I did these as objects because these will have other properties eventually.

    Created array:

     var referenceArray= [];
     for (var key in columns) {
         for (var j in columns[key]){
             referenceArray.push(j);
         }
      }
    

    Used this with result set from database. I don't know how efficient it is but with the few number of columns I used, it worked fine.

    result.forEach((element, index, array) => {                            
        var tr = document.createElement('tr');
        for (var i = 0; i < referenceArray.length - 1; i++) {
            var td = document.createElement('td');
            td.innerHTML = element[referenceArray[i]];
            tr.appendChild(td);
    
        }
        tableBody.appendChild(tr);
    }); 
    
    0 讨论(0)
  • 2020-11-22 04:05
    let sortedOrder = [ 'b', 'c', 'b', 'b' ]
    let itemsArray = [ 
        ['Anne', 'a'],
        ['Bob', 'b'],
        ['Henry', 'b'],
        ['Andrew', 'd'],
        ['Jason', 'c'],
        ['Thomas', 'b']
    ]
    a.itemsArray(function (a, b) {
        let A = a[1]
        let B = b[1]
    
        if(A != undefined)
            A = A.toLowerCase()
    
        if(B != undefined)
            B = B.toLowerCase()
    
        let indA = sortedOrder.indexOf(A)
        let indB = sortedOrder.indexOf(B)
    
        if (indA == -1 )
            indA = sortedOrder.length-1
        if( indB == -1)
            indB = sortedOrder.length-1
    
        if (indA < indB ) {
            return -1;
        } else if (indA > indB) {
            return 1;
        }
        return 0;
    })
    

    This solution will append the objects at the end if the sorting key is not present in reference array

    0 讨论(0)
  • 2020-11-22 04:05

    In case you get here needing to do this with an array of objects, here is an adaptation of @Durgpal Singh's awesome answer:

    const itemsArray = [
      { name: 'Anne', id: 'a' },
      { name: 'Bob', id: 'b' },
      { name: 'Henry', id: 'b' },
      { name: 'Andrew', id: 'd' },
      { name: 'Jason', id: 'c' },
      { name: 'Thomas', id: 'b' }
    ]
    
    const sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]
    
    Object.keys(itemsArray).sort((a, b) => {
      return sortingArr.indexOf(itemsArray[a].id) - sortingArr.indexOf(itemsArray[b].id);
    })
    
    0 讨论(0)
提交回复
热议问题