Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
Convert array of objects into subarrays of objects by a selected property (javascript)

I am looking to take an array of objects, and convert it into an array of subarrays based on a chosen object property

for example:

[
  {foo: 1, bar: a}, {foo: 2, bar: b}, {foo: 1, bar: c}, {foo: 2, bar: d}
]

Create subarrays with the foo property would become:

[
  [
    {foo: 1, bar: a}, {foo: 1, bar: c}, 
  ],
  [
    {foo: 2, bar: b}, {foo: 2, bar: d}
  ]
]

I can't think of an efficient way to this. I keep resorting to creating a set of all of the unique property values of my chosen value, and then brute forcing through it multiple times.

const distinctProperties =  [...new Set(originalArray.map(item => item.foo))]

const newArray = distinctProperties.map(item => originalArray.filter(obj => obj.foo === item))

Thanks in advance for some advice here!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

can be done with reduce. you can wrap this around another function to group by the key you want.

Here I'm grouping based on the value of foo and res will be like this

{
  1: [{
  bar: "a",
  foo: 1
}, {
  bar: "c",
  foo: 1
}],
  2: [{
  bar: "b",
  foo: 2
}, {
  bar: "d",
  foo: 2
}]
}

then I'm taking Object.values of this to get the array format you want

let a =[
  {foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 1, bar: 'c'}, {foo: 2, bar: 'd'}
]

let res= Object.values(a.reduce((acc,curr)=> {
    if(!acc[curr.foo])acc[curr.foo]=[];
  acc[curr.foo].push(curr)
    return acc;
},{}))

console.log(res)

As a generalized function to take key name as input

let a =[
  {foo: 1, bar: 'a'}, {foo: 2, bar: 'b'}, {foo: 1, bar: 'c'}, {foo: 2, bar: 'd'}
]


let groupByValue = (arr,key) => {
    return Object.values(arr.reduce((acc,curr)=> {
    if(!acc[curr[key]])acc[curr[key]]=[];
  acc[curr[key]].push(curr)
    return acc;
},{}))
}

let res1 = groupByValue(a,'foo')
let res2 = groupByValue(a,'bar')
console.log(res1)
console.log(res2)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda