1. 数组排序
1.1 冒泡排序
//将第一个值与身后相邻的值进行比较,若身后相邻的值小则与第一个值交换位置。
const arr = [11, 33, -5, 17, 3, 59, 259, -39, 152];
for (var i = 0; i <= arr.length - 1; i++) {
for (var j = 0; j <= arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
console.log(arr)
2. 选择排序
- 首先在未排序序列中找到最小的元素,存放在排序序列的起始位置。
- 再从剩余未排序元素中继续寻找最小元素,然后放在已经排序列的末尾
- 重复以上步骤.
var arr = [10, 90, 55, 96, 23, 8, 79];
for (var i = 0; i < arr.length - 1; i++) {
var minIndex = i;
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] > arr[minIndex]) {
minIndex = j
}
}
const temp = arr[i];
arr[i] = arr[minIndex]
arr[minIndex] = temp
}
1.2 sort排序
const arr = [11, 33, -5, 17, 3, 59, 259, -39, 152];
arr.sort((a, b) => {
return a - b
})
console.log('2', arr)
2. 数组去重
```javascript //第一种 new Set() const arr1 = [11, 22, 33, 14, 22, 33] const arr2 = […new Set(arr1)] console.log(arr2) //[11, 22, 33, 14]
//第二种 indexOf const arr1 = [11, ‘a’, 22, 33, 14, 22, 33, ‘a’, null] let arr2 = [] arr1.forEach(item => { //如果检索的字符串值没有出现, 则返回-1 if (arr2.indexOf(item) == -1) { arr2.push(item) } }) console.log(arr2) //[11, ‘a’, 22, 33, 14, null]
//第三种 includes const arr1 = [11, ‘a’, 22, 33, 14, 22, 33, ‘a’, null] let arr2 = [] arr1.forEach(item => { //如果检索的字符串值没有出现, 则返回-1 if (!arr2.includes(item)) { arr2.push(item) } }) console.log(arr2) //[11, ‘a’, 22, 33, 14, null]
//第四种 reduce + includes const arr1 = [11, ‘a’, 22, 33, 14, 22, 33, ‘a’, null,33] let arr2 = arr1.reduce((prev, cur) => prev.includes(cur) ? prev : […prev, cur], [])
console.log(arr2) //[11, ‘a’, 22, 33, 14, null]
//第五种 reduce + indexOf const arr1 = [11, ‘a’, 22, 33, 14, 22, 33, ‘a’, null] let arr2 = arr1.reduce((prev, cur) => prev.indexOf(cur) !== -1 ? prev : […prev, cur], [])
console.log(arr2) //[11, ‘a’, 22, 33, 14, null]
//第六种 filter + indexOf const arr1 = [11, ‘a’, 22, 33, 14, 22, 11, ‘a1’, null] let arr2 = arr1.filter((item, index, arr) => { //当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素 return arr.indexOf(item, 0) === index })
console.log(arr2) //[11, ‘a’, 22, 33, 14, ‘a1’,null]
```javascript
var arr = [
{
key: '01',
value: '乐乐',
},
{
key: '02',
value: '博博',
},
{
key: '03',
value: '淘淘',
},
{
key: '04',
value: '哈哈',
},
{
key: '01',
value: '乐乐',
},
]
//第一种方法
let obj = {};
for (var i = 0; i < arr.length; i++) {
obj[arr[i]['key']] = arr[i]
}
console.log(Object.values(obj))
//第二种方式
let obj = {};
let resData = []
arr.forEach(item => {
if (!obj[item['key']]) {
resData.push(item)
obj[item['key']] = true
}
})
//第三种
const obj = new Map();
const resData = arr.filter(item => !obj.has(item['key']) && obj.set(item['key'], 1))
console.log(resData)
//第四种
let resData = []
arr.forEach((item, index) => {
//findIndex作用:找到遍历的数组中的第一个符合判断条件的值,并返回该值对应的索引,停止遍历
const findIndex = arr.findIndex(each => each.key === item.key)
if (findIndex === index) {
resData.push(item)
}
})