js基础算法学习

okgoes 2023-05-09 13:07:19
Categories: Tags:
  1.  移除数组 arr 中的所有值与 item 相等的元素。不要直接修改数组 arr,结果返回新的数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//递归实现
function remove(arr, item) {
    var newArr = arr.slice(0);
    if (newArr.indexOf(item) === -1) {
        return newArr;
    }
    newArr.splice(newArr.indexOf(item), 1)
    return remove(newArr, item);
}
//循环遍历实现
function remove1(arr, item) {
    var newArr = [];
    arr.forEach(function(e, index, arr){
        if(e !== item){
            newArr.push(e);
        }
    })
    return newArr;
}

2.直接在原数组上操作

1
2
3
4
5
6
7
function removeWithoutCopy(arr, item) {
    if (arr.indexOf(item) === -1) {
        return arr;
    }
    arr.splice(arr.indexOf(item), 1)
    return removeWithoutCopy(arr, item);
}

3. 查找数组中重复出现的数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//不改变原数组
function duplicates(arr) {
    var newArr = [];
    arr.forEach(function(e, index){
        if ((arr.slice(index + 1)).indexOf(e) !== -1) {
            if (newArr.indexOf(e) === -1) {
                newArr.push(e);
            }
        }
    });
    return newArr;
}
//第二种方式
function duplicates1(arr) {
    var newArr = [];
    arr.forEach(function(e, index){
        if (arr.indexOf(e) !== arr.lastIndexOf(e) && newArr.indexOf(e) === -1) {
            newArr.push(e);
        }
    });
    return newArr;
}

4. 数组去重

1
2
3
4
5
6
7
8
9
function duplicates2(arr) {
    var newArr = [];
    arr.forEach(function(e, index){
        if (newArr.indexOf(e) === -1) {
            newArr.push(e);
        }
    });
    return newArr;
}

5. 在数组 arr 的 index 处添加元素 item。不要直接修改数组 arr,结果返回新的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function insert(arr, item, index) {
    var newArr = [];
    for (var key in arr) {
        if (key == index) {
            newArr.push(item);
            newArr.push(arr[key]);
        } else {
            newArr.push(arr[key]);
        }
    }
    return !newArr.length ? [item] : newArr;
}


//利用slice+concat
function insert1(arr, item, index) {
    return arr.slice(0,index).concat(item,arr.slice(index));
}
//利用concat +splice
function insert2(arr, item, index) {
    var newArr=arr.concat();
    newArr.splice(index,0,item);
    return newArr;
}
//利用slice+splice
function insert3(arr, item, index) {
    var newArr=arr.slice(0);
    newArr.splice(index,0,item);
    return newArr;
}
//利用push.apply+splice
function insert4(arr, item, index) {
    var newArr=[];
    [].push.apply(newArr, arr);
    newArr.splice(index,0,item);
    return newArr;
}
//普通的迭代拷贝
function insert5(arr, item, index) {
    var newArr=[];
    for(var i=0;i<arr.length;i++){
        newArr.push(arr[i]);
    }
    newArr.splice(index,0,item);
    return newArr;
}