根据对象的某些属性的数组从数组中删除对象

时间:2019-03-07 10:48:41

标签: javascript arrays performance

我有一个对象数组(objList),每个对象都具有“ id”属性。

我有一个字符串数组(idsToRemove),表示要从objList中删除的对象的ID。

我找到了一些解决方案,但我担心它很慢,尤其是对于具有许多属性的大量对象而言。 有更有效的方法吗?

var idsToRemove = ["3", "1"];
var objList = [{
    id: "1",
    name: "aaa"
  },
  {
    id: "2",
    name: "bbb"
  },
  {
    id: "3",
    name: "ccc"
  }
];

for (var i = 0, len = idsToRemove.length; i < len; i++) {
  objList = objList.filter(o => o.id != idsToRemove[i]);
}

console.log(objList);

4 个答案:

答案 0 :(得分:35)

namespace App\Http\Controllers;

use App\Employee; use Illuminate\Http\Request;

class EmployeeController extends Controller {

public function create() { return view('addemployee'); } public function store(Request $request) { $employee = new Employee(); $employee->firstName = $request->get('firstName'); $employee->middleName = $request->get('middleName'); $employee->lastName = $request->get('lastName'); $employee->gender = $request->get('gender'); $employee->city = $request->get('city'); $employee->localAddress = $request->get('localAddress'); $employee->permanentAddress = $request->get('permanentAddress'); $employee->emailAddress = $request->get('emailAddress'); $employee->mobileNumber = $request->get('mobileNumber'); $employee->email = $request->get('email'); $employee->department = $request->get('department'); $employee->designation = $request->get('designation'); $employee->save(); return redirect('addemployee')->with('Success', 'Data Inserted Successfully!'); }
转换为idsToRemove,以便可以使用Set(一项Set.prototype.has操作)和O(1) .filter一次,因此总体复杂度为objList(并且您仅对可能巨大的O(n)进行了一次迭代):

objList

请注意,var idsToRemove = ["3", "1"]; var objList = [{ id: "1", name: "aaa" }, { id: "2", name: "bbb" }, { id: "3", name: "ccc" } ]; const set = new Set(idsToRemove); const filtered = objList.filter(({ id }) => !set.has(id)); console.log(filtered);Array.prototype.includes操作是Array.prototype.indexOf,而不是O(N),因此,如果使用它们代替O(1),它们可能会花费更长的时间

答案 1 :(得分:4)

您可以使用Array.includes来检查给定的字符串是否存在于给定的数组中,并将其与Array.filter组合。

const idsToRemove = ['3', '1'];

const objList = [{
    id: '1',
    name: 'aaa',
  },
  {
    id: '2',
    name: 'bbb',
  },
  {
    id: '3',
    name: 'ccc',
  },
];

const filteredObjList = objList.filter(x => !idsToRemove.includes(x.id));

console.log(filteredObjList);

答案 2 :(得分:3)

如果使用内置的查找功能,则不需要两个嵌套的迭代器

   objList = objList.filter(o => idsToRemove.indexOf(o.id) < 0);

文档:

Array.prototype.indexOf()

Array.prototype.includes()

答案 3 :(得分:1)

只需使用Array.filter()

const idsToRemove = ['3', '1'];

const objList = [{
    id: '1',
    name: 'aaa',
  },
  {
    id: '2',
    name: 'bbb',
  },
  {
    id: '3',
    name: 'ccc',
  }
];

const res = objList.filter(value => !idsToRemove.includes(value.id));

console.log("result",res);