Home > other >  Find partial string text in array object
Find partial string text in array object

Time:07-06

Example: If I use the code below it works for the whole word "gorilla".

How do I get it to work with "gor" or "illa" or "orill"...?

...(equivalent to a str like "%gor%" in mysql for example)

const jungle = [
  { name: "frog", threat: 0 },
  { name: "monkey", threat: 5 },
  { name: "gorilla", threat: 8 },
  { name: "lion", threat: 10 }
];

const names = jungle.map(el => el.name);

// returns true
document.write(names.includes("gorilla"));

CodePudding user response:

You can use find (or filter)

const jungle = [
  { name: "frog", threat: 0 },
  { name: "monkey", threat: 5 },
  { name: "gorilla", threat: 8 },
  { name: "lion", threat: 10 }
];

const names = (partial) => jungle.find(el => el.name.includes(partial)).name;

//You can also use "filter" method ==> 

//const names = (partial) => jungle.filter(el => el.name.includes(partial)).map(el => el.name) 



console.log(names("gor"))
console.log(names("illa"))
console.log(names("orill"))

CodePudding user response:

const jungle = [
  { name: "frog", threat: 0 },
  { name: "monkey", threat: 5 },
  { name: "gorilla", threat: 8 },
  { name: "lion", threat: 10 }
];
console.log(jungle.some(({name}) => "gorilla".includes(name))); // returns true

CodePudding user response:

You need to find the object where the name includes the (partial) string, and return the name; otherwise return a default error string.

const jungle = [
  { name: "frog", threat: 0 },
  { name: "monkey", threat: 5 },
  { name: "gorilla", threat: 8 },
  { name: "lion", threat: 10 }
];

function finder(jungle, str) {
  return jungle.find(obj => {
    return obj.name.includes(str);
  })?.name || 'No animal found';
}

console.log(finder(jungle, 'gor'));
console.log(finder(jungle, 'pas'));
console.log(finder(jungle, 'illa'));
console.log(finder(jungle, 'og'));
console.log(finder(jungle, 'nk'));

Additional documentation

CodePudding user response:

Use Array.filter to find all matches (or Array.find if you just want the first match).

Use String.match so that the search string can be either a string or a RegEx, the latter giving you the ability to use wildcards, exact match or more complex criteria.

const jungle = [
    { name: "frog", threat: 0 },
    { name: "monkey", threat: 5 },
    { name: "gorilla", threat: 8 },
    { name: "lion", threat: 10 }
];

// find the animal whose name matches the regular expression

function findAnimal(name) {
    return jungle.filter(animal => animal.name.match(name));
}

console.log(findAnimal('gorilla'));
console.log(findAnimal('on'));
console.log(findAnimal(/^gor/));
console.log(findAnimal(/illa$/));

  • Related