Sorting an array that contains the value of some weights using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of string that contains weights with three units: grams (G), kilo-grams (KG) and tonnes (T). Our function should sort the array into order of weight from light to heavy.

We are required to write a JavaScript function that takes in an array of string that contains weights with three units: grams (G), kilo-grams (KG) and tonnes (T). Our function should sort the array into order of weight from light to heavy.

Example

Following is the code −

 Live Demo

const arr = ['1456G', '1KG', '.5T', '.005T', '78645G', '23KG'];
const arrangeWeights = (arr = []) => {
   const sorted=(w)=>{
      if(w.slice(-2) === 'KG'){
         return +w.slice(0,-2) * 1;
      }else if(w.slice(-1)==='T'){
         return +w.slice(0, -1)*1000
      }else{
         return +w.slice(0, -1)*0.001;
      };
   };
   return arr.sort((a, b) => sorted(a) - sorted(b));
};
console.log(arrangeWeights(arr));

Output

[ '1KG', '1456G', '.005T', '23KG', '78645G', '.5T' ]

Updated on: 19-Apr-2021

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements