1

I have an issue with my array. I didn't find a similar case on the forum so I'm asking for help here.

Here is an example of what I got, and what I want in output.

input :

var array = 
  [
   {scanned_time : '2020-01-01 12:00:00',
   client : 11111,
   code : 'A11111'},

   {scanned_time : '2020-01-01 12:00:00',
   client : 11111,
   code : 'A22222'},

   {scanned_time : '2020-01-01 12:00:00',
   client : 22222,
   code : 'A33333'},

   {scanned_time : '2020-01-02 12:00:00',
   client : 11111,
   code : 'A4444'}
]

"scanned_time" and "client" are kind of unique pair.

The output I would need :

var result =
[
 ['2020-01-01 12:00:00', 11111, 'A11111', 'A22222'],
 ['2020-01-01 12:00:00', 22222, 'A33333'],
 ['2020-01-02 12:00:00', 11111, 'A44444']
]

I tried multiple things using map, reduce etc but I wasn't able to find anything, I'm not even close.

Thanks in advance!

EDIT :

Starting point :

let result = array.reduce(function (r, a) {
        r[a.scanned_time] = r[a.scanned_time] || [];
        r[a.scanned_time].push(a);
        return r;
    }, Object.create(null));

which give me

{
  '2020-10-26T13:33:00.000Z': [
    {
      AD_code: '852589',
      scanned_time: 2020-10-26T13:33:00.000Z,
      client_code: '12385'
    },
    {
      AD_code: '951478',
      scanned_time: 2020-10-26T13:33:00.000Z,
      client_code: '12385'
    }
  ],
  '2020-10-26T13:32:00.000Z': [
   {
      AD_code: '369874',
      scanned_time: 2020-10-26T13:32:00.000Z,
      client_code: '12385'
    }
  ]
}
3
  • Can you add the attempts you made as a starting point? Commented Oct 29, 2020 at 4:16
  • var result = array.map(a => Object.values(a)); Commented Oct 29, 2020 at 4:18
  • Hi, welcome to StackOverflow. Please provide a Minimal, Complete, and Reproducible code example. Without code, there isn't much anyone can do. Commented Oct 29, 2020 at 4:23

1 Answer 1

1

You can use simple for loop to achieve this, I did some work around this. Try it out!

var array = 
  [
   {scanned_time : '2020-01-01 12:00:00',
   client : 11111,
   code : 'A11111'},

   {scanned_time : '2020-01-01 12:00:00',
   client : 11111,
   code : 'A22222'},

   {scanned_time : '2020-01-01 12:00:00',
   client : 22222,
   code : 'A33333'},

   {scanned_time : '2020-01-02 12:00:00',
   client : 11111,
   code : 'A4444'}
]
const result = []
for(const obj of array) {
  const acc = result.find(c => c.includes(obj.scanned_time) && c.includes(obj.client))
  if (!acc) {
      result.push([obj.scanned_time.toString(), obj.client, obj.code])
  } else {
    acc.push(obj.code)
  }
}

console.log(result)

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

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.