One quick question regarding filter method. Is it possible to return multiple values using JavaScript filter method So, I was wondering is it possible to loop through json and filter values using something like this...
var arr = [{
name: 'John',
email: 'johnson@mail.com',
age: 25,
address: 'USA'
},
{
name: 'Tom',
email: 'tom@mail.com',
age: 35,
address: 'England'
},
{
name: 'Mark',
email: 'mark@mail.com',
age: 28,
address: 'England'
}
];
// filter array by name Mark and Tom
const result = arr.filter(function (el) {
return el.name === 'Mark' && el.name ==='Tom';
});
And end result would be something like this:
[Object { name: "Mark", email: "mark@mail.com", age: 28, address: "England" },{ name: "Tom", email: "tom@mail.com", age: 35, address: "England" }]
Is something like this possible and if not what is your best method/approach?
In the function you pass to filter
, you want to check if the name equals "Mark" OR "Tom". That will return an array with the two objects that match.
var arr=[{name:'John',email:'johnson@mail.com',age:25,address:'USA'},{name:'Tom',email:'tom@mail.com',age:35,address:'England'},{name:'Mark',email:'mark@mail.com',age:28,address:'England'}] // filter array by name Mark and Tom const result = arr.filter(function (el) { return el.name === 'Mark' || el.name === 'Tom'; }); console.log(result)
filters
take an array and returns a subset array of the elements matching some condition.
You have to provide a function that is true
for the elements you want to get, and false
for the others.
The only missing thing in your function is that you need to use ||
(logical OR) instead of &&
(and)
const result = arr.filter(function (el) {
return el.name === 'Mark' || el.name === 'Tom';
});
because an element can have its name equals to Mark OR Tom, but no element has it's name equals to Mark AND Tom at the same time.
const arr = [{ name: 'John', email: 'johnson@mail.com', age: 25, address: 'USA' }, { name: 'Tom', email: 'tom@mail.com', age: 35, address: 'England' }, { name: 'Mark', email: 'mark@mail.com', age: 28, address: 'England' }]; const selectedNames = ["Mark", "Tom"]; const result = arr.filter(({ name }) => selectedNames.includes(name)); console.log(result);
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.