2

I have an array of objects and want to filter it based on values of another string array and remove the objects that doesn't contain any of the strings.

I tried using split for the string array and search for each term in a forEach but it didn't work then tried the following which works as a filter but it filters for exact match not partial.

var employees = [
  {"name": "zxc asd", "age":"30"},
  {"name": "asd", "age":"24"},
  {"name": "qwe", "age":"44"},
  {"name": "zxc", "age":"28"},
];

var keepNames = ["asd", "qwe"];

keepNames = keepNames.map(name => {
  return name.toLowerCase();
});


var filteredEmployees = employees.filter(emp => {
  return keepNames.indexOf(emp.name.toLowerCase()) !== -1;
});

console.log( filteredEmployees );

Expected Output[  
  {"name": "zxc asd", "age":"30"},
  {"name": "asd", "age":"24"},
  {"name": "qwe", "age":"44"}];

Actual Output [
  {"name": "asd", "age":"24"},
  {"name": "qwe", "age":"44"}]

I'd really appreciate any help. Thanks in advance

2
  • 1
    btw, removeNames is misleading, becuase tis array has the keeping names. Commented Oct 5, 2019 at 16:52
  • yes i noticed after i posted the question, i used removeNames as i was trying the opposite at first then forgot to rename it. Commented Oct 5, 2019 at 17:05

2 Answers 2

4

You need to iterate the array with names keep as well and check the value.

var employees = [{ name: "zxc asd", age: "30" }, { name: "asd", age: "24" }, { name: "qwe", age: "44" }, { name: "zxc", age: "28" }],
    keep = ["asd", "qwe"],
    filtered = employees.filter(({ name }) =>
        keep.some(n => name.toLowerCase().includes(n))
    );

console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

1

indexOf uses strict equality so it won't match partially.

You can use some and includes

var employees = [ {"name": "zxc asd", "age":"30"},{"name": "asd", "age":"24"},{"name": "qwe", "age":"44"},{"name": "zxc", "age":"28"},];
var filterBy = ["asd", "qwe"];

var filteredEmployees = employees.filter(emp => {
  return filterBy.some(v => emp.name.toLowerCase().includes(v.toLowerCase()))
});

console.log(filteredEmployees);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.