Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find item in array in React

I want to retrieve data from a json file and then match it with the value of an existing variable and if the variable value matches the data in json it will display a message "a" and if it does not match it will display a message "b".

the json file is like this

["23435","87567", "34536","45234","34532","65365"]
like image 922
lostboii999 Avatar asked Nov 18 '25 12:11

lostboii999


1 Answers

What you want is to find a value in an array.

You can use includes

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.includes(aConstant) ? 'a' : 'b' }</div>)

Same thing with indexOf

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.indexOf(aConstant) !== -1 ? 'a' : 'b' }</div>)

You can also try filter

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ Boolean(array.filter( x => x === aConstant)) ? 'a' : 'b' }</div>)

And even find

    const array = ["23435","87567", "34536","45234","34532","65365"]

    const aConstant = "23435"

    return (<div>{ array.find( x => x === aConstant) ? 'a' : 'b' }</div>)
like image 148
Someone Special Avatar answered Nov 20 '25 00:11

Someone Special



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!