0

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

1 Answer 1

1

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)
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.