0

i have an array like so,

const array = ["item1/1", "item2/3", "item3/4"]

now i want to loop through these array elements one by one and get only the values from the strings i.e., from first array element "item1/1" should get 1 and put it to an output array similarly for array element 2 "item2/3" should get 3 and put it to output array. similarly for array element "item3/4" should get 4 and put it to output array.

so the expected output array should be ["1", "3", "4"]

i have tried below,

const find = React.useMemo(() => {
    if (arr.length >= 0) {
            
        const match = arr[0].match(/([\w-]+)\/([^/]+)\/$/);
        if (match) return [match[2]];
    }
}, [arr])

but above code does for one array element. how can i loop through array and push the return match in an output array.

i am new to programming. could someone help me with this. thanks.

1
  • 1
    Why are you using memo? Commented Jan 19, 2022 at 13:17

1 Answer 1

2

You can iterate over your array by map method, and on every itration split your string by / character, then just returining the secion after /. like this:

const array = ["item1/1", "item2/3", "item3/4"]
const result = array.map(str => str.split('/').pop())
console.log(result)

Sign up to request clarification or add additional context in comments.

1 Comment

It would be safer to use .pop() instead of [1], to get the last item regardless of how many there are.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.