I have an array containing various strings like:
let arr = ["cap:1", "col:red", "cap:3", "cap:1", "col:blue", "screen:yes"]
and I'm looking to create a new array with one item from each category of substrings ("cap", "col", "screen"), choosing the one with the smallest index:
let newArray = ["cap:1","col:red","screen:yes"]
//"cap:1" which is taken from arr[0]
I've attempted solving this problem in the following way:
const newArr = (arr) => {
let c= []
let c = [...c, arr[0]]
for(let i = 1; i<arr.length; i++){
for (let j=0; j<c.length; j++){
if(arr[i].split(":")[0] !== c[j].split(":")){
c = [...c, arr[i]]
}
}
}
return c
}
However, this approach leads to an infinite loop and results in output like:
["cap:1","col:red","col:red","col:red","col:red","col:red","col:red","col:red"...
Could someone please assist me with this issue?Thank you!