# 操作数组不要只会for循环

## reduce

### 数组里所有值的和

```var sum = [0, 1, 2, 3].reduce(function (a, b) {
return a + b;
}, 0);
// sum is 6```

### 将二维数组转化为一维数组

```var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function (a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]```

### 计算数组中每个元素出现的次数

```var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }```

### 使用扩展运算符和initialValue绑定包含在对象数组中的数组

```// friends - an array of objects
// where object field "books" - list of favorite books
var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];

// allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(function (prev, curr) {
return [...prev, ...curr.books];
}, ['Alphabet']);

// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]```

### 数组去重

```var arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
var result = arr.sort().reduce(
function (init, current) {
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current);
}
return init;
},
[]
);
console.log(result); //[1,2,3,4,5]```

### 数组变整数

```var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
return x * 10 + y;
}); // 13579```

## map

### 求数组中每个元素的平方根

```var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]```

### 格式化数组中的对象

```var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];

var reformattedArray = kvArray.map(function (obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});

// reformattedArray 数组为： [{1: 10}, {2: 20}, {3: 30}],

// kvArray 数组未被修改:
// [{key: 1, value: 10},
//  {key: 2, value: 20},
//  {key: 3, value: 30}]```

### 用一个仅有一个参数的函数来mapping一个数字数组

```var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});

// doubles数组的值为： [2, 8, 18]
// numbers数组未被修改： [1, 4, 9]```

### 反转字符串

```var str = '12345';
Array.prototype.map.call(str, function(x) {
return x;
}).reverse().join('');

// 输出: '54321'
// Bonus: use '===' to test if original string was a palindrome```

## every

### 检测所有数组元素的大小

```function isBigEnough(element, index, array) {
return (element >= 10);
}

var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true```

## filter

### 筛选排除掉所有的小值

```function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]```

## find

### 用对象的属性查找数组里的对象

```var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];

function findCherries(fruit) {
return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }```

### 寻找数组中的质数

```function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}

console.log([4, 5, 8, 12].find(isPrime)); // 5```

## some

### 测试数组元素的值

```function isBigEnough(element, index, array) {
return (element >= 10);
}

var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true```

## sort

### 使用映射改善排序

```// 需要被排序的数组
var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];

// 对需要排序的数字和位置的临时存储
var mapped = list.map(function (el, i) {
return {index: i, value: el.toLowerCase()};
})

// 按照多个值排序数组
mapped.sort(function (a, b) {
return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// 根据索引得到排序的结果
var result = mapped.map(function (el) {
return list[el.index];
});```

52 篇文章26 人订阅

0 条评论

## 相关文章

### 1798: [Ahoi2009]Seq 维护序列seq

1798: [Ahoi2009]Seq 维护序列seq Time Limit: 30 Sec  Memory Limit: 64 MB Submit: 2930...

3065

1153

931

6516

### [C#1] 8-数组

1.数组概述 声明数组： //每个元素初始化为0，虽然数组元素是值类型，但是却是分配在托管堆中的； int[] myArray=new int[100]; //...

1937

842

1794

2383

### Scala集合练习题

//创建一个List val list0 = List(1,7,9,8,0,3,5,4,6,2) //将list0中每个元素乘以10后生...

4619

1110