Let's say I have an array like this:
var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']
How would I get an array that tells me what position each of them is at? for example:
var reds = [1,2,3,5], blues = [0,4,6,7]
So far I have tried to use the indexOf(); function but that will only return 1 of the values if there are multiple matches.
You could collect all indices in an object with the color as property.
This approach features
a classic for statement for iterating the index,
a logical nullish assignment ??= to check the property and assign an array if not given,
and Array#push, to get the index into the array with the color as name.
const
colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'],
indices = {};
for (let i = 0; i < colors.length; i++) {
(indices[colors[i]] ??= []).push(i);
}
console.log(indices);
You can use forEach, for loop to get the element and index and push it into respective array.
var colors = ["blue", "red", "red", "red", "blue", "red", "blue", "blue"];
const reds = [];
const blues = [];
colors.forEach((color, index) => {
if (color === "red") reds.push(index);
else if (color === "blue") blues.push(index);
});
console.log(reds);
console.log(blues);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With