If i have an array:
[{month:'January', value:1},{month:'February', value:2}]
and so on how can i check if month in array includes for example Jan and then return 1, Feb return 2 and so on?
Any suggestion?
Is this what you want? You can create a regular expression and test it.
If your search should be case insensitive, change the RegExp as follows,
const pattern = new RegExp("^" + month, 'i');
Note that ^
matches the start of a string without consuming any characters.
const array = [{ month: 'January', value: 1 }, { month: 'February', value: 2 }]; function findValue(month) { const pattern = new RegExp("^" + month); const m = array.find(c => pattern.test(c.month)); return m && m.value || null; } console.log(findValue("Jan")) console.log(findValue("Feb"))
const monthsArray = [{month:'January', value:1},{month:'February', value:2}]; const month = 'Jan'; console.log(monthsArray.find(m => m.month.includes(month)))
(credit to Hamza Khanzada in the comment).
Includes
on a String property will check whether the prop has the value you are checking for in it, and will return a match or undefined.
You can leverage that further with a wrapper function as in the other answer
Is this what you are looking for?
This essentially does a case-insensitive search.
let monthToFind = 'jan'; let input = [{month:'January', value:1},{month:'February', value:2}]; let result = input.find(x => x.month.toLowerCase().includes(monthToFind.toLowerCase()))?.value; console.log(result);
if you want to validate that the month starts with
const months = [{ month: 'January', value: 1 }, { month: 'February', value: 2 }]; function matchMonth(intialsMonth) { return months.find(res => res.month.toLowerCase().startsWith(intialsMonth.toLowerCase())).value; } console.log(matchMonth("Jan")); console.log(matchMonth("Feb"));
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.