Home > front end >  Sort an array based on the other array
Sort an array based on the other array

Time:10-20

I am trying to sort a list with reference to another list. Consider this example,

var array1 = [1,2,3,4,5,6];
var array2 = [4,6,3];

Now, I want the result to be like this,

result = [4,6,3,1,2,5];  

How can I achieve this result?

CodePudding user response:

how about

 var array1 = [1,2,3,4,5,6];
 var array2 = [4,6,3];
 
 var result = [...array2.where((i) => array1.contains(i)), ...array1.where((i) => !array2.contains(i))];

print('resulting array: ${result}');

The first part collects everything in array2 that lives in the first array, the second part collect everything not in the second array aka the missing values

CodePudding user response:

    <script>
    var array1 = [1,2,3,4,5,6];
    var array2 = [4,8,3];
    var sayac=1;
    for(var i=0;i<array2.length;i  ){
            if(array1.indexOf(array2[i])==-1){
            array1[array1.length sayac]=array2[i];
                sayac  ;
              }
    }
        console.log(array1);
    
    
    </script>
  • Related