How to pass string literal to filter function in JavaScript


random IT

I want to pass string literal to filter function.

The result should be

filter = data.filter(o => o.tag.toLowerCase().indexOf(("website").toLowerCase()) != -1 &&
          o.tag.toLowerCase().indexOf(("phone").toLowerCase()) != -1

What I am currently doing is

  • Get all labels in an array using for loop
  • Form string query and execute filter in array
  • The problem is when the filter is passed, it returns everything, which means string literals don't work
for (let i = 0; i < values.length; i++) {
          if (i + 1 >= values.length) {
            query = query.concat(` o.tag.toLowerCase().indexOf(("${values[i]}").toLowerCase()) != -1 `);
          } else {
            query = query.concat(` o.tag.toLowerCase().indexOf(("${values[i]}").toLowerCase()) != -1 && `);
          }

        }
let filter = data.filter(o => `${query}`);
        debugger;


The sample snippet I am trying to filter. I want to make this filter function dynamic

data=[{name:"fpl.xlsx",author:"hello",hits:6,date:"2020-01-01",tag:"logo,website"}
,{name:"corporate.pptx",author:"hellob",hits:1,date:"2020-02-01",tag:"logo"},
{name:"index.html",author:"hellob",hits:7,date:"2020-02-02",tag:"logo,abc"}

]

let filter=[];
filter=data.filter(o=>o.tag.indexOf("logo")!=-1 && o.tag.indexOf("abc")!=-1)

console.log(filter);

VLAZ

If you want to make sure that all the valuesmatches that are in one project tag, then you can use to do that.Array#every

const arr1 = ["aardvark", "ant", "alien"];
const arr2 = ["apple", "audi", "bcoccoli"];

const startsWithA = word => word[0] === "a";

console.log(arr1.every(startsWithA));
console.log(arr2.every(startsWithA));

Also, this method can be used instead, since it returns a boolean value directly.String#includes.indexOf

const word = "applesauce";

console.log(word.includes("apple"));
console.log(word.includes("sauce"));

So we get this:

const data = [{name:"fpl.xlsx",author:"hello",hits:6,date:"2020-01-01",tag:"logo,website"}
,{name:"corporate.pptx",author:"hellob",hits:1,date:"2020-02-01",tag:"logo"},
{name:"index.html",author:"hellob",hits:7,date:"2020-02-02",tag:"logo,abc"}]

const values = ["logo", "abc"];

let result = data
  .filter(
    ({tag}) => values.every(
        value => tag.toLowerCase()
            .includes(value.toLowerCase())
     ) 
  )
  
console.log(result);

However, tagyou may get false positives due to the inclusion of a comma-separated list:

const tag1 = "foobar";
const tag2 = "foo,bar";

const values = ["foo", "bar"];

console.log(values.every(value => tag1.includes(value)));
console.log(values.every(value => tag2.includes(value)));

A token might be a word that is made up of multiple other words that match, and you just want to do an exact match. You can separate the labels with , and you just need to find if the two arrays overlap:String#split

const tag1 = "foobar";
const tag2 = "foo,bar";

const values = ["foo", "bar"];

const arrayOfTag1 = tag1.split(",");
const arrayOfTag2 = tag2.split(",");

console.log(values.every(value => arrayOfTag1.includes(value)));
console.log(values.every(value => arrayOfTag2.includes(value)));

Collections can be used to reduce the complexity of the overall lookup, in this case filtering looks like this:

const data = [{name:"fpl.xlsx",author:"hello",hits:6,date:"2020-01-01",tag:"logo,website"}
,{name:"corporate.pptx",author:"hellob",hits:1,date:"2020-02-01",tag:"logo"},
{name:"index.html",author:"hellob",hits:7,date:"2020-02-02",tag:"logo,abc"}]

const values = ["logo", "abc"];

let result = data
  .filter(
    ({tag}) => {
      const lookupTags = new Set(
        tag
          .split(",")
          .map(x => x.toLowerCase())
      );
    
      return values.every(value => lookupTags.has(value.toLowerCase())
     )
   })
  
console.log(result);

Related


How to pass string literal to filter function in JavaScript

random IT I want to pass string literal to filter function. The result should be filter = data.filter(o => o.tag.toLowerCase().indexOf(("website").toLowerCase()) != -1 && o.tag.toLowerCase().indexOf(("phone").toLowerCase()) != -1 What I am currently

How to pass string literal to filter function in JavaScript

random IT I want to pass string literal to filter function. The result should be filter = data.filter(o => o.tag.toLowerCase().indexOf(("website").toLowerCase()) != -1 && o.tag.toLowerCase().indexOf(("phone").toLowerCase()) != -1 What I am currently

How to pass string literal to filter function in JavaScript

random IT I want to pass string literal to filter function. The result should be filter = data.filter(o => o.tag.toLowerCase().indexOf(("website").toLowerCase()) != -1 && o.tag.toLowerCase().indexOf(("phone").toLowerCase()) != -1 What I am currently

How to pass string literal to filter function in JavaScript

random IT I want to pass string literal to filter function. The result should be filter = data.filter(o => o.tag.toLowerCase().indexOf(("website").toLowerCase()) != -1 && o.tag.toLowerCase().indexOf(("phone").toLowerCase()) != -1 What I am currently

How to pass string literal to filter function in JavaScript

random IT I want to pass string literal to filter function. The result should be filter = data.filter(o => o.tag.toLowerCase().indexOf(("website").toLowerCase()) != -1 && o.tag.toLowerCase().indexOf(("phone").toLowerCase()) != -1 What I am currently

Pass string literal to template function

scarecrow I try to specifically target several types of template functions, one of which is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<con

Pass string literal to template function

scarecrow I try to specifically target several types of template functions, one of which is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<con

Pass string literal to template function

scarecrow I try to specifically target several types of template functions, one of which is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<con

Pass string literal to template function

scarecrow I try to specifically target several types of template functions, one of which is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<con

Pass string literal to template function

scarecrow I try to specifically target several types of template functions, one of which is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<con

Pass string literal to template function

scarecrow I try to specifically target several types of template functions, one of which is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<con

How to pass string to dplyr filter in function?

James 131 I'm looking for a way to pass a string as input to a function in the dplyr package in filter_my own function. I have the dataframe set up as follows: df = data.frame( X1 = LETTERS[1:5], X2 = c("apple", "apple", "apple", "banana", "banana") )

How to pass string to dplyr filter in function?

James 131 I'm looking for a way to pass a string as input to a function in the dplyr package in filter_my own function. I have the dataframe set up as follows: df = data.frame( X1 = LETTERS[1:5], X2 = c("apple", "apple", "apple", "banana", "banana") )

How to pass string to dplyr filter in function?

James 131 I'm looking for a way to pass a string as input to a function in the dplyr package in filter_my own function. I have the dataframe set up as follows: df = data.frame( X1 = LETTERS[1:5], X2 = c("apple", "apple", "apple", "banana", "banana") )

How to pass string to dplyr filter in function?

James 131 I'm looking for a way to pass a string as input to a function in the dplyr package in filter_my own function. I have the dataframe set up as follows: df = data.frame( X1 = LETTERS[1:5], X2 = c("apple", "apple", "apple", "banana", "banana") )

How to pass a function to an array literal?

other How can I pass an array without making it a separate variable? For example, I know this works: class Test{ public static void main(String[] args){ String[] arbitraryStrings={"foo"}; takesStringArray(arbitraryStrings); } public

How to pass string parameter to javascript function

arrow Here is my front end: ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id String strApplication1 = Details.CommandArgument.ToString(); e.Row.Attributes["onmouseover"] = "this.style.cursor='

How to pass string from HTML to Javascript function?

karunagara I have a dynamic Html table with a cell containing anchor tags. In addition to the anchor tag, I also called a function via the OnClick method . The function has two parameters, both of type String . where a string contains the value "PUT Request|GE

How to pass Javascript as string to HTML function

Swish 20599 I'm trying to replicate some Javascript code using functions. Among them, it is triggered by HTMLcode . It doesn't work because double quotes for the presence scriptmark close the onclickattribute. function copytext(data){ var t

How to pass string as parameter to javascript function

Kiran Gopalakrishnan What I need is to be able to pass a string to a javascript function which is specified in the div's onclick event, $("#div").html("<div id='suggestion' onclick='storetag("+response[i]['tagname']+")'><div id='postag' ><center><b>"+response[

How to pass string variable in Javascript function?

wild eagle Here is my code: JSP: String userId = rs.getString("user_id"); <center><a href="#" onclick="edit(\'' + userId + '\');">Edit</a></center> JavaScript: function edit(id) { alert(" user id is "+id); } But it doesn't work. It gives the e

How to pass string as parameter to javascript function

Kiran Gopalakrishnan What I need is to be able to pass a string to a javascript function which is specified in the div's onclick event, $("#div").html("<div id='suggestion' onclick='storetag("+response[i]['tagname']+")'><div id='postag' ><center><b>"+response[

How to pass string variable in Javascript function?

wild eagle Here is my code: JSP: String userId = rs.getString("user_id"); <center><a href="#" onclick="edit(\'' + userId + '\');">Edit</a></center> JavaScript: function edit(id) { alert(" user id is "+id); } But it doesn't work. It gives the e

Pass array to JavaScript filter function

cat and mouse Suppose I have an array of objects like this: someObj: [ { name: "Obj1", type: "a" }, { name: "Obj2", type: "b" }, { name: "Obj3", type: "c" } ] Now I have a function

Pass array to JavaScript filter function

cat and mouse Suppose I have an array of objects like this: someObj: [ { name: "Obj1", type: "a" }, { name: "Obj2", type: "b" }, { name: "Obj3", type: "c" } ] Now I have a function

Pass array to JavaScript filter function

cat and mouse Suppose I have an array of objects like this: someObj: [ { name: "Obj1", type: "a" }, { name: "Obj2", type: "b" }, { name: "Obj3", type: "c" } ] Now I have a function

Javascript to pass parameters to filter function?

tadm123 I want to remove all elements with the same value as these parameters from the initial array. predecessor: destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1]. destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1]. Here is my code: funct

Pass string to javascript function

pizza sauce Simple question. How can I pass a string to a javascript function and have a popup alert with the content of that string? Here is what I have: test.html.erb file. <%= link_to 'Test','#', onclick: 'test(helloworld)', class: "btn btn-xs btn-primary"