Javascript - sort array based on another array

后端 未结 22 1446
鱼传尺愫
鱼传尺愫 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: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);
    }); 
    

提交回复
热议问题