zoukankan      html  css  js  c++  java
  • 13 种在 JavaScript 中删除/过滤数组的方法【转】

    英文 | https://javascript.plainenglish.io/13-methods-to-remove-filter-an-item-in-an-array-and-array-of-objects-in-javascript-f02b71206d9d

    翻译 | 杨小爱

    我们可能总是会遇到根据一个属性或多个属性值从数组或对象数组中删除项目的时候,今天让我们看看根据属性值从数组中删除或过滤项目有哪些不同的方法。

    1、POP

    “pop() 方法从数组中删除最后一个元素并返回该元素。这个方法改变了数组的长度。” (来源:MDN)

    数组:

    let arraypoptest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let testpop = arraypoptest.pop();
    console.log("array pop", testpop,"-", arraypoptest);
    // 10 - [2, 1, 2, 5, 6, 7, 8, 9, 9];
    

    对象数组:

    let users1 = [
      { id: 1, name: "ted" },
      { id: 2, name: "mike" },
      { id: 3, name: "bob" },
      { id: 4, name: "sara" }
    ];
    let testpop1 = users1.pop();
    console.log("array of objects pop", JSON.stringify(testpop1),"-" JSON.stringify(users1));
    // {"id":4,"name":"sara"} - [{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]
    

    2、Shift()

    “shift() 方法从数组中移除第一个元素并返回移除的元素。这个方法改变了数组的长度。” (来源:MDN)

    数组:

    let arrayshifttest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let testshift = arrayshifttest.shift();
    console.log("array shift", testshift,"-", arrayshifttest);
    // 2 - [1, 2, 5, 6, 7, 8, 9, 9, 10]
    

    对象数组:

    let users2 = [
      { id: 1, name: "ted" },
      { id: 2, name: "mike" },
      { id: 3, name: "bob" },
      { id: 4, name: "sara" }
    ];
    let testshift1 = users2.shift();
    console.log("array of objects shift", JSON.stringify(testshift1),"-", JSON.stringify(users2));
    // {"id":1,"name":"ted"} - [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]
    

    3、slice

    “slice() 方法将数组的一部分的浅拷贝返回到从开始到结束(不包括结束)选择的新数组对象中,其中开始和结束表示该数组中项目的索引。不会修改原始数组。” (来源:MDN)

    数组:

    let arrayslicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let testslice = arrayslicetest.slice(0, 3);
    console.log("array slice", testslice, arrayslicetest);
    //not changed original array
    //[2, 1, 2] - [2, 1, 2, 5, 6, 7, 8, 9, 9, 10]
    

    对象数组:

    let users3 = [
    { id: 1, name: "ted" },
    { id: 2, name: "mike" },
    { id: 3, name: "bob" },
    { id: 4, name: "sara" }
    ];
    let testslice1 = users3.slice(0, 3);
    console.log("array of objects slice", JSON.stringify(testslice1));
    // not changed original array
    // [{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]
    

    4、splice

    “ splice() 方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。” (来源:MDN)

    数组:

    let arraysplicetest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let testsplice = arrayslicetest.splice(0, 3);
    

    对象数组:

    let users4 = [
      { id: 1, name: "ted" },
      { id: 2, name: "mike" },
      { id: 3, name: "bob" },
      { id: 4, name: "sara" }
    ];
    let testspice1 = users3.splice(0, 3);
    console.log("array of objects splice", JSON.stringify(testsplice));
    // [{"id":1,"name":"ted"},{"id":2,"name":"mike"},{"id":3,"name":"bob"}]
    

    5、使用 splice 删除特定值

    数组:

    let arr = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] === 5) {
        arr.splice(i, 1);
      }
    }
    console.log("splice with specific value", arr);
    //[2, 1, 2, 6, 7, 8, 9, 9, 10]
    

    对象数组:

    let users5 = [
    { id: 1, name: "ted" },
    { id: 2, name: "mike" },
    { id: 3, name: "bob" },
    { id: 4, name: "sara" }
    ];
    for (var i = 0; i < users5.length; i++) {
      if (users5[i].name === "ted") {
        users5.splice(i, 1);
      }
    }
    console.log("splice with specific value array of objects",JSON.stringify( users5));
    // [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]
    

    6、使用 splice 删除特定值 — 简写

    “ splice() 方法通过删除或替换现有元素,或在适当位置添加新元素来更改数组的内容。”(来源:MDN)

    “indexOf() 方法返回可以在数组中找到给定元素的第一个索引,如果不存在,则返回 -1。”(来源:MDN)

    数组:

    let arrShorthand = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let val = arr.indexOf(5);
    arrShorthand.splice(val, 1);
    console.log("splice shorthand specific value", arrShorthand);
    //[1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    对象数组:

    let users6 = [
    { id: 1, name: "ted" },
    { id: 2, name: "mike" },
    { id: 3, name: "bob" },
    { id: 4, name: "sara" }
    ];
    var removeIndex = users6.map(item => item.id).indexOf(1);
    users6.splice(removeIndex, 1);
    console.log("splice shorthand specific value array of objects", JSON.stringify(users6));
    // [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]

    7、Filter

    “filter() 方法创建一个新数组,其中包含所有通过所提供函数实现的测试的元素。”(来源:MDN)

    数组:

    let testarr = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let testarr2 = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let filtered = testarr.filter(function(value, index, arr) {
      return value > 5;
    });
    let filtered2 = testarr2.filter(item => item !== 2);
    console.log("filter example 1", filtered);
    // [6, 7, 8, 9, 9, 10]
    console.log("filter example 2", filtered2);
    // [1, 5, 6, 7, 8, 9, 9, 10]
    

    删除多个值的过滤器:

    let forDeletion = [2, 3, 5];
    let mularr = [1, 2, 3, 4, 5, 3];
    mularr = mularr.filter(item => !forDeletion.includes(item));
    console.log("multiple value deletion with filter", mularr); //[1, 4]
    

    对象数组:

    let users7 = [
    { id: 1, name: "ted" },
    { id: 2, name: "mike" },
    { id: 3, name: "bob" },
    { id: 4, name: "sara" }
    ];
    let filterObj = users7.filter(item => item.id !== 2);
    console.log("filter example array of objects", filterObj);
    // [{"id":1,"name":"ted"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]
    

    8、delete operator

    “JavaScript delete 操作符从对象中删除一个属性;如果不再持有对同一属性的更多引用,它最终会自动释放。”(来源:MDN)

    let ar = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    delete ar[4];
    // delete element with index 4 console.log(ar);
    //[2, 1, 2, 5, undefined, 7, 8, 9, 9, 10]
    

    9、lodash remove

    _remove “从数组中删除谓词返回真值的所有元素,并返回已删除元素的数组。谓词使用三个参数调用:(值、索引、数组)。” (来源:lodash)

    数组:

    let arrlodashtest = [2, 1, 2, 5, 6, 7, 8, 9, 9, 10];
    let evens = _.remove(arrlodashtest, function(n) {
      return n % 2 == 0;
    });
    console.log("lodash remove array", arrlodashtest);
    // [1, 5, 7, 9, 9]
    

    对象数组:

    let users8 = [
      { id: 1, name: "ted" },
      { id: 2, name: "mike" },
      { id: 3, name: "bob" },
      { id: 4, name: "sara" }
    ];
    let evensObj = _.remove(users8, function(n) {
      return n.id % 2 == 0;
    });
    console.log("lodash remove array of object", JSON.stringify(evensObj));
    // [{"id":2,"name":"mike"},{"id":4,"name":"sara"}]
    

    10、对象实用程序

    “Object.entries() 方法返回给定对象自己的可枚举字符串键控属性 [key, value] 对的数组,其顺序与 for...in 循环提供的顺序相同。” (来源:MDN)

    const object = [1, 2, 3, 4];
    const valueToRemove = 3;
    const arrObj = Object.values(Object.fromEntries(Object.entries(object).filter(([key, val]) => val !== valueToRemove) ));
    console.log("object utilites", arrObj); // [1,2,4]
    

    11、 lodash filter

    _filter “迭代集合的元素,返回所有元素的数组,谓词返回真值。谓词使用三个参数调用:(值、索引|键、集合)。” (来源:lodash)

    let users10 = [
      { id: 1, name: “ted” },
      { id: 2, name: “mike” },
      { id: 3, name: “bob” },
      { id: 4, name: “sara” }
    ];
    const lodashFilter = _.filter(users10, { id: 1 });
    console.log(“lodash filter”, JSON.stringify(lodashFilter));
    // [{"id":1,"name":"ted"}]
    

    12、lodash without

    _without “返回过滤值的新数组。” (来源:lodash)

    let lodashWithout = [2, 1, 2, 3];
    let lodashwithoutTest = _.without(lodashWithout, 1, 2);
    console.log(lodashwithoutTest); //[3]
    

    13、lodash reject

    _reject “与 _.filter 做相反的事情,这个方法返回predicate不返回真值的集合元素。”(来源:lodash)

    let users9 = [
      { id: 1, name: "ted" },
      { id: 2, name: "mike" },
      { id: 3, name: "bob" },
      { id: 4, name: "sara" }
    ];
    const result = _.reject(users9, { id: 1 });
    console.log("lodash reject", result);
    // [{"id":2,"name":"mike"},{"id":3,"name":"bob"},{"id":4,"name":"sara"}]
    

    总结

    以上就是我今天与你分享的内容,如果你觉得对你有所帮助,请记得点赞,并且分享给你身边做开发的朋友。

    最后,感谢你的阅读,祝编程愉快!

    ---------------------------------------------
    生活的意义并不是与他人争高下,而在于享受努力实现目标的过程,结果是对自己行动的嘉奖。
    ↑面的话,越看越不痛快,应该这么说:

    生活的意义就是你自己知道你要做什么,明确目标。没有目标,后面都是瞎扯!
  • 相关阅读:
    Ubuntu 14.04 LTS Server 无法挂载光盘 启动initramfs等问题
    Linux的交叉编译 及configure配置
    大话设计模式读书笔记(五) 代理模式
    大话设计模式读书笔记(三) 单一职责原则和开放-封闭原则和依赖倒转原则
    大话设计模式读书笔记(二) 策略模式
    Java NIO(一) 初步理解NIO
    大话设计模式读书笔记(一) 简单工厂模式
    多线程设计模式(一) Single Threaded Execution
    多线程详细解析(二) 线程的共享互斥与线程的协调
    多线程详细解析(一) 创建线程
  • 原文地址:https://www.cnblogs.com/pengchenggang/p/15538338.html
Copyright © 2011-2022 走看看