0

I have an array of tokens:

[
    {type: 'name', value: 'foo'},
    {type: 'string', value: 'bar'},
    {type: 'special', value: ','},
    {type: 'name', value: 'buzz'}
]

And I'd like to split them by value equal to ,:

[
    [
        {type: 'name', value: 'foo'},
        {type: 'string', value: 'bar'}
    ],
    [
        {type: 'name', value: 'buzz'}
    ]
]

How should I do it?

2
  • 1
    What have you tried? What specifically do you need help with? Commented Dec 8, 2018 at 13:14
  • Well, the only thing that comes to mind is iterating through the array and putting the objects in an array inside that array, then when a comma is encountered, another array is started. There must be a better way, but I can't really wrap my head around it.. Commented Dec 8, 2018 at 13:16

2 Answers 2

2

You can use Array.reduce() to iterate the items. There are three cases:

  1. The item's value is , - add a new sub-array without the item.
  2. There is no sub-array - add a new sub-array with the item.
  3. The rest - add the item to the last sub-array.

const data = [
    {type: 'name', value: 'foo'},
    {type: 'string', value: 'bar'},
    {type: 'special', value: ','},
    {type: 'name', value: 'buzz'}
];

const result = data.reduce((r, o) => {
  if(o.value === ',') return [...r, []];
  if(!r.length) return [[o]];
  
  r[r.length - 1].push(o);
  
  return r;
}, []);

console.log(result);

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

Comments

1

Using forEach

let arr = [
    {type: 'name', value: 'foo'},
    {type: 'string', value: 'bar'},
    {type: 'special', value: ','},
    {type: 'name', value: 'buzz'}
]

let op = [];
let temp = [];
arr.forEach((e,i)=>{
  if(e.value === ',' && temp.length){
    op.push(temp);
    temp =[];
  } else {
    temp.push(e);
  }
});
if(temp.length) op.push(temp);
console.log(op);

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.