原生javscript方法—数组篇(去重和排序)
去重
var arr = [1, 2, 3, true, true, "a", "b", "c", 4, 3, 0, false, true, false, "c", "b"];
- 双重for循环+splice删除重复
function arrRemoveRepeat1(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
console.log(arrRemoveRepeat1(arr));
- 利用sort()的排序,先排序后去重
function arrRemoveRepeat2(arr) {
arr = arr.sort();
console.log(arr);
var array = [arr[0]];
for (var i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
array.push(arr[i]);
}
}
return array;
}
console.log(arrRemoveRepeat2(arr));
- Map数据结构去重
function arrRemoveRepeat3(arr) {
let map = new Map();
let array = new Array();
for (let i = 0; i < arr.length; i++) {
if (map.has(arr[i])) {
map.set(arr[i], true);
} else {
map.set(arr[i], false);
array.push(arr[i]);
}
}
return array;
}
console.log(arrRemoveRepeat3(arr));
- indexOf去重
function arrRemoveRepeat4(arr) {
let array = [];
for (let i = 0; i < arr.length; i++) {
if (array.indexOf(arr[i]) === -1) {
array.push(arr[i])
}
}
return array;
}
console.log(arrRemoveRepeat4(arr));
- filter
function arrRemoveRepeat5(arr) {
let newArr = arr.filter((v, i, arr)=>{
return arr.indexOf(v, 0) === i;
});
return newArr;
}
console.log(arrRemoveRepeat5(arr));
- ES6中的Set
function arrRemoveRepeat6(arr){
return Array.from(new Set(arr))
}
console.log(arrRemoveRepeat6(arr));
排序
- sort大法
function arrSort1(arr) {
arr.sort(function(a, b) {
return a - b;
});
return arr
}
console.log(arrSort1(arr));
- 冒泡排序
function arrSort2(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
console.log(arrSort2(arr));
- 选择排序
function arrSort3(arr) {
length = arr.length;
var min;
var temp;
for (var i = 0; i < length; i++) {
min = i;
for (var j = i; j < length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
return arr;
}
console.log(arrSort3(arr));
- 插入排序
function arrSort4(arr) {
var length = arr.length;
var str;
for (var i = 0; i < length; i++) {
str = arr[i];
for (var j = i; j > 0 && str < arr[j - 1]; j--) {
arr[j] = arr[j - 1];
arr[j - 1] = str;
}
}
return arr;
}
console.log(arrSort4(arr));