Javascript - sort array based on another array

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

提交回复
热议问题