lmg1114
lmg1114

Reputation: 193

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.

Upvotes: 3

Views: 3669

Answers (6)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

The answer of Nina Scholz looks good. And I want to give another way to help you.

You can use Array#reduce to resolve it with the highest performance O(n) time complexity like below:

const colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue']

const result = colors.reduce((acc, color, index) => {
  acc[color] ??= [];
  acc[color].push(index);
  
  return acc;
}, {});
console.log(result);

Upvotes: 0

Simon_B
Simon_B

Reputation: 61

You can also use reduce to construct an object where the properties are your colors and the values an array with the indexes

const colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'];

const indices = colors.reduce((acc, color, index) => {
    return !acc[color] ? 
             { ...acc, [color]: [index]} :
             { ...acc, [color]: [...acc[color], index] }
}, {})

console.log(indices);

Upvotes: 0

Brent Owen
Brent Owen

Reputation: 19

let arr1 = ['blue', 'red', 'blue', 'red', 'red', 'blue', 'blue'];

const redElements = arr1.filter(x => x == 'red');

const blueElements = arr1.filter(x => x == 'blue');

Filter returns an array;

Upvotes: -1

anton-tchekov
anton-tchekov

Reputation: 1098

I think this will be easier to understand than the other answers:

var colors = ['blue', 'red', 'red', 'red', 'blue', 'red', 'blue', 'blue'];

var reds = [];
var blues = [];

for(var i = 0; i < colors.length; ++i)
{
    if(colors[i] == 'red')
    {
        reds.push(i);
    }
    else if(colors[i] == 'blue')
    {
        blues.push(i);
    }
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You could collect all indices in an object with the color as property.

This approach features

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);

Upvotes: 8

DecPK
DecPK

Reputation: 25408

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);

Upvotes: 3

Related Questions