Desenv Junior
Desenv Junior

Reputation: 141

How to reduce an array of objects with two properties into two arrays, one for each property?

I have an array of objects with two properties: canais and topicos:

 channel: Array(3)
    0: {canais: 'canal1', topicos: 'topico1'}
    1: {canais: 'canal2', topicos: 'topico2'}
    2: {canais: 'canal3', topicos: 'topico3'}

I want to split into two array of strings called canais and topicos:

canais : [ "canal1" , "canal2", "canal3" ];
topicos: [ "topico1" , "topico2", "topico3" ];

Upvotes: 0

Views: 928

Answers (3)

Marco Bonelli
Marco Bonelli

Reputation: 69276

You could do this in multiple ways:

  1. Map each element to a 2-element array [canais, topicos] and then transpose the result to get two arrays (here original is your array):

    const transpose = arr => arr[0].map((x, i) => arr.map(x => x[i]))
    const [canais, topicos] = transpose(original.map(a => [a.canais, a.topicos]))
    

    See also: Transposing a 2D-array in JavaScript which is the origin of the transpose function above.

  2. Use a forEach loop and accumulate:

    const canais = []
    const topicos = []
    
    original.forEach(el => {
        canais.push(el.canais)
        topicos.push(el.topicos)
    })
    
  3. Normal for loop and accumulate:

    const allCanais = []
    const allTopicos = []
    
    for (const {canais, topicos} of original) {
        allCanais.push(canais)
        allTopicos.push(topicos)
    }
    
  4. Map two times (first extract all el.canais then all el.topicos), though this iterates twice over the data which is probably unneeded.

Upvotes: 2

Jesse
Jesse

Reputation: 1424

If you need it to be dynamic, you can use a nested for loop to go through each item and create/add to arrays based on the key, then use an object to store each array of values.

let channelNames = {};
for(let c of channel){
    for(let key in c){
        if(!channelNames[key])
            channelNames[key] = [];
        channelNames[key].push(i[key]);
    }
}

Upvotes: -1

Vítor França
Vítor França

Reputation: 767

You can do

const canais = channel.map(item => item.canais)
const topicos = channel.map(item => item.topicos)

Upvotes: 3

Related Questions