I’m a newbie in JavaScript so any suggestion would be much appreciated.
I have this array:
var mixedArray = [["online","abc","def"],["offline","ghi","jkl"],["online","mno","pqr"],["offline","stu","vwx"] ]
I want to output like this:
var array1 = [["online","abc","def"],["online","mno","pqr"]]
var array2 = [["offline","ghi","jkl"],["offline","stu","vwx"]]
Is there any method to make that solution?
Thank you in advance
4
Answers
One way you could group these arrays, assuming each group is either
online
oroffline
uses Array.filterIf you can support the new
Object.groupBy
method (which there are polyfills for if you can’t), then you can use that to create an object where each"offline"
array is grouped to the keyoffline
and each"online"
array is grouped to the keyonline
, once done, you can destructure theoffline
andonline
values from this grouped object to use them as separate arrays:Here is an example alternative if you can’t support
.groupBy
, where you can create your own implementation:You can use
Array.reduce
to create a grouping of elements based on the first item in each rowAn one-liner would do it easily.
The task seems as splitting an array into two based on a boolean flag (represented as ‘online’/’offline’). You can use
Array::reduce()
: