[Javascript ] Array methods in depth - sort
Sort can automatically arrange items in an array. In this lesson we look at the basics including how to sort an array of strings alphabetically and the correct way to perform a numerical sort on an array of numbers. We finish as always with a practical use-case that shows not only sort in action, but also how it can be chained together with other array methods such as map and join.
Problem with sort number in Array:
var data = [10, 20, 15];
var sorted = data.sort(); console.log(sorted); // [10, 15, 20]
Code works fine, but there is a problem:
When calling sort on an array with numbers, what actually happens is each number is converted to a string, and they're compared using their position in Unicode.
var data = [10, 20, 15, 30 ,2];
var sorted = data.sort(); console.log(sorted); // [10, 15, 2, 20, 30]
This is because, in Unicode, 10 does come before 2. Again, this is because these numbers are being converted to strings first.
To solve the problem:
var data = [10, 20, 15, 30 ,2];
var sorted = data.sort( (a,b)=>{
return a-b;
} ); console.log(sorted);
We need to provide a comparative function to make it work. If a - b < 0 then it just put a before b;
Also according to that, we can compare the lenght of string, then sort them in order:
var sorted = names.sort( (a,b)=>{
return a.length - b.length;
} );
console.log(sorted); // ["Bob", "Kent", "Kettly", "Jusnine"]
A more useful example : sort objects
var list = lessons.sort( (a,b)=>{
return a.views-b.views
} )
.map( (lession)=>{
return ` <li>${lession.title} - ${lession.views}</li>`;
} )
.join('\n');
var output = `<ul>\n${list}\n</ul>`;
console.log(output);
/*
"<ul>
<li>Javascript Array methods in depth - concat - 1000</li>
<li>Javascript Array methods in depth - join - 1025</li>
<li>Javascript Array methods in depth - slice - 1050</li>
</ul>"
*/
[Javascript ] Array methods in depth - sort的更多相关文章
- [Javascript] Array methods in depth - filter
Array filter creates a new array with all elements that pass the test implemented by the provided fu ...
- [Javascript] Array methods in depth - slice
Array slice creates a shallow copy of an array. In this lesson we cover, in detail, exactly what a ' ...
- [Javascript] JavaScript Array Methods in Depth - push
Array push is used to add elements to the end of an Array. In this lesson we'll see how the push met ...
- [Javascript] Array methods in depth - indexOf
indexOf is used to search for a value or reference inside of an array. In this lesson we first look ...
- [Javascript] Array methods in depth - some
some returns a boolean value after passing each item in the source array through the test function t ...
- JavaScript Array methods performance compare
JavaScript Array methods performance compare JavaScript数组方法的性能对比 env $ node -v # v12.18.0 push vs un ...
- javascript Array Methods(学习笔记)
ECMAScript 5 定义了9个新的数组方法,分别为: 1.forEach(); 2.map(); 3.filter(); 4.every(); 5.some(); 6.reduce() ...
- JavaScript Array 对象
JavaScript Array 对象 Array 对象 Array 对象用于在变量中存储多个值: var cars = ["Saab", "Volvo", & ...
- JavaScript Array(数组)对象
一,定义数组 数组对象用来在单独的变量名中存储一系列的值. 创建 Array 对象的语法: new Array(); new Array(size); new Array(element0, elem ...
随机推荐
- 学习C++——只声明忘记定义了
#include <iostream> #include <list> #include <string> using namespace std; class E ...
- How to scroll the window using JQuery $.scrollTo() function
$('html, body').animate({scrollTop: $("#page").offset().top}, 2000); http://stackoverflow. ...
- 文件操作-php
<?php /* 建立缓存 可以用文件长时间保存数据 文件是以liunux为模型的 在Windows下只能获取file ,dir unknow linux 下可以获取block char dir ...
- 1 Two Sum(找和为target的两个数字下标Medium)
题目意思:给一个数组,找到和为target的两个元素的序号,并且只有一组这样的元素 思路:map<int,int>(nums[i],i+1),然后从后往前循环,用count找,比较i+1 ...
- jQuery1.6以上版本prop和attr的区别
- javascript 向上滚动
<html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Co ...
- php 手机电话正则表达式验证
function check_telnum1($telnum) { $b1 = (preg_match(" ...
- jquery ajax(3).post
.post返回文本数据 $(function(){ $("#send").click(function(){ $.post("post1.php", { use ...
- 模拟DOMContentLoaded事件
window.onload事件 文档中所有图片,脚本,链接以及子框完成加载后,才会触发window.onload事件. 浏览器兼容性:All DOMContentLoaded事件 当页面中的文档树解析 ...
- JavaScript and html的关系
HTML--------------------------->DOM, BOM, Event Request/Response------------->Ajax 日期处理 http:/ ...