

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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' ]
- Related Questions & Answers
- Sorting an array that contains undefined in JavaScript?
- Sorting according to weights of numbers in JavaScript
- Sorting an array of objects by an array JavaScript
- Sorting an array of literals using quick sort in JavaScript
- Sorting an array of binary values - JavaScript
- Alternative sorting of an array in JavaScript
- Creating an array using a string which contains the key and the value of the properties - JavaScript
- Sorting an array object by property having falsy value - JavaScript
- Sorting and find sum of differences for an array using JavaScript
- Sorting only a part of an array JavaScript
- Sorting binary string having an even decimal value using JavaScript
- Sorting an array objects by property having null value in JavaScript
- JavaScript Return an array that contains all the strings appearing in all the subarrays
- Sorting an array of objects by property values - JavaScript
- Matching an array field that contains any combination of the provided array in MongoDB?
Advertisements