How to loop through an array and put the result to an array using react and javascript?
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.
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)