Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getting an array from the index of another array

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.

like image 659
lmg1114 Avatar asked May 29 '26 00:05

lmg1114


2 Answers

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);
like image 121
Nina Scholz Avatar answered May 30 '26 14:05

Nina Scholz


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);
like image 35
decpk Avatar answered May 30 '26 13:05

decpk



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!