1

I am very new in javascript and I am trying to flatten attribute in an object which save in an array of objects.

[
 {
  addr: addrvalue1,
  events: [1,2],
 },
 {
  addr: addrvalue2,
  events: [1],
 }
]

I want to convert objects above to

[{
 addr: addrvalue1,
 events: 1,
}
{
 addr: addrvalue1,
 events: 2,
}
{
 addr: addrvalue2,
 events: 1,
}]

And then sort them by event value, so they will finally be like

[{
     addr: addrvalue1,
     events: 1,
    }
{
     addr: addrvalue2,
     events: 1,
    }
    {
     addr: addrvalue1,
     events: 2,
    }
]

For now I am using multiple for-loops for to do this, but I think there would be some more elegant way doing this. Thanks in advance.

3 Answers 3

2

You can use Array.flatMap() to iterate the objects and flatten the results, and an internal Array.map() to create the arrays of event objects. Then you can sort them by the event.

const data = [{"addr":"addrvalue1","events":[1,2]},{"addr":"addrvalue2","events":[1]}]

const result = data.flatMap(({ addr, events }) => events.map(event => ({
    event,
    addr
  })))
  .sort((o1, o2) => o1.event - o2.event)
  
console.log(result)

Sign up to request clarification or add additional context in comments.

2 Comments

Good use of flatMap
Because flatMap is not supported by IE and Edge. If you need a support for those browsers use @kemicofa's answer.
1

Use Array#reduce with Array#concat

const data = [{
    addr: 111,
    events: [1, 2],
  },
  {
    addr: 222,
    events: [1],
  }
];

const result = data.reduce((acc, {addr, events})=>{
  return acc.concat(events.map(item=>({addr, events: item})));
}, []);

console.log(result.sort((a,b)=>a.events-b.events));

Comments

0

Something like this?

var output=[],
    data=[
 {
  addr: "addrvalue1",
  events: [1,2],
 },
 {
  addr: "addrvalue2",
  events: [1],
 }
]
for(obj of data){
  for(i in obj.events){
    output.push({addr:obj.addr,events:parseInt(i)+1})
  }
}
output.sort(function(a,b){return a.events-b.events})
console.log(output)

I hope it will helps :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.