Skip to content

Commit ad66d31

Browse files
adding 61
1 parent 4e207e3 commit ad66d31

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,3 +2237,52 @@ const isAvgWhole = (arr) =>{
22372237
22382238
---
22392239
**[⬆ Back to Top](#header)**
2240+
2241+
2242+
2243+
##### 61.Create a function that takes an array of strings and return an array, sorted from shortest to longest.
2244+
2245+
2246+
```js
2247+
const sortByLength = (arr) =>{
2248+
//Write Your solution Here
2249+
};
2250+
2251+
console.log(sortByLength(["a", "ccc", "dddd", "bb"])) //["a", "bb", "ccc", "dddd"]
2252+
2253+
console.log(sortByLength(["apple", "pie", "shortcake"])) //["pie", "apple", "shortcake"]
2254+
2255+
console.log(sortByLength(["may", "april", "september", "august"])) //["may", "april", "august", "september"]
2256+
2257+
```
2258+
2259+
<details><summary style="cursor:pointer">Solution</summary>
2260+
2261+
```js
2262+
const sortByLength = (arr) => {
2263+
return arr.sort(function (a,b){return a.length - b.length})
2264+
}
2265+
2266+
2267+
const sortByLength = (arr) => {
2268+
const n = arr.length;
2269+
2270+
for (let i = 0; i < n - 1; i++) {
2271+
for (let j = 0; j < n - i - 1; j++) {
2272+
if (arr[j].length > arr[j + 1].length) {
2273+
2274+
const temp = arr[j];
2275+
arr[j] = arr[j + 1];
2276+
arr[j + 1] = temp;
2277+
}
2278+
}
2279+
}
2280+
2281+
return arr;
2282+
};
2283+
```
2284+
2285+
</details>
2286+
2287+
---
2288+
**[⬆ Back to Top](#header)**

0 commit comments

Comments
 (0)