Home > Mobile >  How to compare a partial string input from a json array
How to compare a partial string input from a json array

Time:10-21

I have a json with below structure. I want to compare input with below elements each (Key/values) of json and return the response only if atleast one word matched from input to the compared string of JSON.

input: "Angular work space"

json:

[{id:1,name:"angular repo"},{id:2,name:"node repo"}]

first row in above json should be returned as 1 phrase is matching.

CodePudding user response:

You can use a regex with Array.filter to achieve this

const data = [{id:1,name:"angular repo"},{id:2,name:"node repo"}]

const inputStr = "Angular work space";

const regex = new RegExp(`(^| )(${inputStr.split(" ").join('|')})( |$)`, 'gi')

const result = data.filter(({name}) => regex.test(name))
console.log(regex, result)

CodePudding user response:

You can split the user input into words (using split) and map it to lowerCase for comparison.

Finnaly, you just need to filter your initial JSON array to check if one word is matching.

In the bellow implementation i've used the includes method which return the string if it is contains in one of the word.

const json = [{id:1,name:"angular repo"},{id:2,name:"node repo"}]

const checkInput = (value) => {
  const words = value.split(' ').map(x => x.toLowerCase())
  
  const matchingJson = json.filter(json => words.some(word => json.name.includes(word)))
  
  return matchingJson
}


console.log(checkInput("Angular work space"))

CodePudding user response:

You could use regex and case-insensitive flag for this

The regex would be (pattern analysis)

/\b(Angular|work|space)\b/gi

const input = "Angular work space"
const regex = new RegExp(`\\b${input.split(" ").join("|")}\\b`, "gi")
const data = [
  { id: 1, name: "angular repo" },
  { id: 2, name: "node repo" },
  { id: 2, name: "angular space" },
  { id: 2, name: "work company" },
]

const res = data.filter(d => d.name.match(regex))

console.log(res)

  • Related