1

I was trying to insert arrays into array, for example I have

var objList = [
  {
    name: jack,
    status: ''
  },
  {
    name: mark,
    status: yes
  },
  {
    name: erik, 
    status: no
  },
  {
    name: mike,
    status: yes
  },
  {
    name: chaze,
    status: no
  }
]

what I want is everytime that it finds 'status:yes' it will push it to new array with the following 'status:or'. it would look something like this

[[{name: jack, status: ''}], [{name: mark, status: yes},{name: erik, status: no}], [{name: mike, status: yes},{name: chaze, status: no}]]
1
  • 1
    What exactly is your problem? Seems like just looping over your array and then applying your logic would simply solve your problem? Commented Sep 24, 2018 at 7:30

1 Answer 1

3

You could reduce the array and check if the status is yes, then add a new sub array to the result set. Then just add the object to the last array.

var data = [{ name: 'jack', status: '' }, { name: 'mark', status: 'yes' }, { name: 'erik', status: 'no' }, { name: 'mike', status: 'yes' }, { name: 'chaze', status: 'no' }],
    result = data.reduce((r, o) => {
        if (!r.length || o.status === 'yes') {
            r.push([]);
        }
        r[r.length - 1].push(o);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

2 Comments

thanks, this is what I'm looking for. Will mark it as correct answer :)
It might be cleaner to start with [[]] and skip the length check. I suppose that might not be right if the data is empty, but it certainly feels a bit cleaner.

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.