skip to Main Content

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


  1. One way you could group these arrays, assuming each group is either online or offline uses Array.filter

    var mixedArray = [["online","abc","def"],["offline","ghi","jkl"],["online","mno","pqr"],["offline","stu","vwx"] ]
    array1 = mixedArray.filter((item) => item[0] == "online");
    array2 = mixedArray.filter((item) => item[0] == "offline");
    
    Login or Signup to reply.
  2. If 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 key offline and each "online" array is grouped to the key online, once done, you can destructure the offline and online values from this grouped object to use them as separate arrays:

    const mixedArray = [["online","abc","def"],["offline","ghi","jkl"],["online","mno","pqr"],["offline","stu","vwx"] ]
    const { online, offline } = Object.groupBy(mixedArray, ([onOrOff]) => onOrOff);
    
    console.log(online); // array1
    console.log(offline); // array2

    Here is an example alternative if you can’t support .groupBy, where you can create your own implementation:

    const mixedArray = [["online","abc","def"],["offline","ghi","jkl"],["online","mno","pqr"],["offline","stu","vwx"] ]
    const { online, offline } = groupBy(mixedArray, ([onOrOff]) => onOrOff);
    
    console.log(online); // array1
    console.log(offline); // array2
    
    // Rough implementation of Object.groupBy (https://tc39.es/proposal-array-grouping/#sec-object.groupby)
    function groupBy(arr, fn) {
      const obj = Object.create(null);
      let k = 0;
      for(const val of arr) {
        const key = fn(val, k++);
        
        if (key in obj) obj[key].push(val);
        else obj[key] = [val];
      }
      return obj;
    }
    Login or Signup to reply.
  3. You can use Array.reduce to create a grouping of elements based on the first item in each row

    var mixedArray = [
      ["online", "abc", "def"],
      ["offline", "ghi", "jkl"],
      ["online", "mno", "pqr"],
      ["offline", "stu", "vwx"]
    ];
    
    const groupedBy = mixedArray.reduce((groups, array) => {
      const key = array[0];
      if (groups[key]) {
        groups[key].push(array)
      } else {
        groups[key] = [array]
      }
      return groups;
    }, {});
    
    console.log(groupedBy);
    Login or Signup to reply.
  4. An 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():

    const arr = [["online","abc","def"],["offline","ghi","jkl"],["online","mno","pqr"],["offline","stu","vwx"]];
    
    const [array1, array2] = arr.reduce((r, item) => (r[+(item[0] === 'offline')].push(item), r), [[],[]]);
    
    console.log(...array1.map(JSON.stringify));
    console.log(...array2.map(JSON.stringify));
    ` Chrome/119
    -----------------------------------------------------------
    Alexander      1.00x  |  x10000000  232  237  240  242  245
    Gabriele       3.04x  |  x10000000  705  708  711  724  728
    Nick Parsons   3.13x  |  x10000000  727  739  747  747  758
    -----------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    const arr = [["online","abc","def"],["offline","ghi","jkl"],["online","mno","pqr"],["offline","stu","vwx"]];
    
    // @benchmark Nick Parsons
    
    // Rough implementation of Object.groupBy (https://tc39.es/proposal-array-grouping/#sec-object.groupby)
    function groupBy(arr, fn) {
      const obj = Object.create(null);
      let k = 0;
      for(const val of arr) {
    const key = fn(val, k++);
    
    if (key in obj) obj[key].push(val);
    else obj[key] = [val];
      }
      return obj;
    }
    
    groupBy(arr, ([onOrOff]) => onOrOff);
    
    // @benchmark Gabriele
    
    arr.reduce((groups, array) => {
      const key = array[0];
      if (groups[key]) {
        groups[key].push(array)
      } else {
        groups[key] = [array]
      }
      return groups;
    }, {});
    
    // @benchmark Alexander
    
    arr.reduce((r, item) => (r[+(item[0] === 'offline')].push(item), r), [[],[]]);
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search