Amir Farahani
Amir Farahani

Reputation: 394

how to group and Separate object of array

how to group and Separate object of an array that comes from the server. array like this: (MOVINGSTATE s This means that Stop andm moving. XPOINT and YPOINT This means that latitude and longitude of car.)

[{MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},
{MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583},
{MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316},..]

I want to if some MOVINGSTATE Continuous s goto new array and when MOVINGSTATE change to mgoto new array and again MOVINGSTATEchange to s goto new array. all this new array object of another main array. i use loadash

var aaa = _loadash.groupBy(props,'MOVINGSTATE')

but Output this :

{m:Array(2),s:Array(3)}

i want outpust like this:

[
 [
  {MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},
  {MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275}
  ],
 [
  {MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},
  {MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583}
 ],
 [
  {MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316}
 ]
]

how to this thanks for helping

Upvotes: 0

Views: 31

Answers (1)

Ravi Kukreja
Ravi Kukreja

Reputation: 647

Try this:

let arr = 
[{MOVINGSTATE: "s",XPOINT:53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "s",XPOINT: 53.9172866,YPOINT: 26.518275},
{MOVINGSTATE: "m",XPOINT: 54.0215383,YPOINT: 26.5275599},
{MOVINGSTATE: "m",XPOINT: 54.0102666,YPOINT: 26.4989583},
{MOVINGSTATE: "s",XPOINT: 54.0016599,YPOINT: 26.5478316}];

  let result =  arr.reduce( (accumulator, cur) => {
    const key = cur["MOVINGSTATE"];
    const keyExists = accumulator.find(obj => obj.key === key);
    if (!keyExists) {
      accumulator.push({key,value:[cur]});
      return accumulator;      
    } else if(accumulator[accumulator.length -1] && accumulator[accumulator.length -1].key === key){
        accumulator[accumulator.length -1].value.push(cur);
        return accumulator;
    } else {
      accumulator.push({key,value:[cur]});
      return accumulator; 
    }
        
  }, [])
  .map(obj => obj.value)

Upvotes: 1

Related Questions