I have this following keys array:
var keys = [{userId: "333"}, {userId: "334"}]
And this objects array:
var users = [
{id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""},
{id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""}
]
I need to change my users Array
by filter it with my keys Array
[inverse result].
Cant figure it out, get all the answers! (js, jquery, angular)
Anyone?
You can use filter()
and find()
.
var users = [ {id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""} ] var keys = [{userId: "333"}, {userId: "334"}] var result = users.filter(function(o) { return !keys.find(function(e) { return e.userId == o.id }) }) console.log(result)
You can have an array of id
s and then you can just check for availability in this list
var users = [ {id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""} ] var keys = [{userId: "333"}, {userId: "334"}] var idList = keys.map(function(x){ return x.userId}); var r = users.filter(function(x){ return idList.indexOf(x.id) < 0 }) console.log(r)
You could use a hash table for filtering.
var keys = [{ userId: "333" }, { userId: "334" }], users = [{ id: "333", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "334", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "335", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "336", firstName: "", lastName: "", idCard: "", birthDate: "" }], filtered = users.filter(function (a) { return !this[a.id]; }, keys.reduce(function (r, a) { r[a.userId] = true; return r; }, Object.create(null))); console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.