欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

数组常用函数解析

程序员文章站 2022-06-26 09:14:43
sort: 用in-place 算法对数组的元素进行排序,并返回数组 语法: arr.sort(comparefunction) comparefunction 可选,如果省略...

sort: 用in-place 算法对数组的元素进行排序,并返回数组

语法: arr.sort(comparefunction)
comparefunction 可选,如果省略,元素根据字符串unicode码点进行默认排序
comparefunction(a, b) 小于 0 ,那么 a 会被排列到 b 之前
comparefunction(a, b) 等于 0 , a 和 b 的相对位置不变(不保证所有顺序一定这样)
comparefunction(a, b) 大于 0 , b 会被排列到 a 之前

码点参考:https://www.ruanyifeng.com/blog/2014/12/unicode.html

(1)比较数字

var number = [21,37,45,-12,0,37];
// number.sort((a,b) => a - b); //升序排列
number.sort((a,b) => b - a); //降序排列
console.log(number); //[45, 37, 37, 21, 0, -12]

(2) 比较对象

 var items = [
       { name: 'edward', value: 21 },
       { name: 'sharpe', value: 37 },
       { name: 'and', value: 45 },
       { name: 'the', value: -12 }, 
       { name: 'magnetic',value: 0 },
       { name: 'zeros', value: 37 } 
];
items.sort( (a, b) => a.value - b.value);

map

语法:array.map(function(value, index, array) {// ...});

(1) 原数组被“映射”成对应新数组

var data = [1, 2, 3, 4];
var arrayofsquares = data.map(function (item) {
    return item * item;
});
console.log(arrayofsquares); // 1, 4, 9, 16

(2) 获得对象数组中的特定属性值

var users = [
    {name: "张一", "email": "zhang@email.com"},
    {name: "江二",   "email": "jiang@email.com"},
    {name: "李三",  "email": "li@email.com"}
];
var emails = users.map(function (user) { return user.email; });
console.log(emails.join(", ")); // zhang@email.com, jiang@email.com, li@email.com 

(3)向对象数组新增属性

 var users = [
    {name: "张一", "email": "zhang@email.com"},
    {name: "江二",   "email": "jiang@email.com"},
    {name: "李三",  "email": "li@email.com"}
 ];
 users  = users.map(function (user,index) { 
       user.index = index;
       return user; 
 });
 console.log(json.stringify(users)); // [{"name":"张一","email":"zhang@email.com","index":0},{"name":"江二","email":"jiang@email.com","index":1},{"name":"李三","email":"li@email.com","index":2}]