- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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' ]
Advertisements