Search code examples
javascriptarraysformatting

Adding " / ", "or", and "and" text after joining the arrays


I have an array of nested arrays and need to join them using the " / ", " or " and " and " text.

If within the same array then joined by " and ".

If sibling then joins by " or ".

Otherwise, join by " \ ".

Example 1:-

The output should be:

ARTH 332 / HIST 364 and HIST 365

[
  [
    [
      "ARTH 332"
    ]
  ]
  [
    [
      "HIST 364"
      "HIST 365"
    ]
  ]
]

Example 2:-

The output should be:

BUS 300 / BUS 310 / BUS 330 / MKT 300 / ACCT 301 / MGMT 362 / BUS 345 or BUS 340

[
  [
    [
      "BUS 300"
    ]
  ]
  [
    [
      "BUS 310"
    ]
  ]
  [
    [
      "BUS 330"
    ]
  ]
  [
    [
      "MKT 300"
    ]
  ]
  [
    [
      "ACCT 301"
    ]
  ]
  [
    [
      "MGMT 362"
    ]
  ]
  [
    [
      "BUS 345"
    ]
    [
      "BUS 340"
    ]
  ]
]

Solution

  • Simply iterate over the array and differentiate between the three cases for and, or and nothing. Finally join the result on /. I have also added , to make the given data a valid array.

    let y = [
      [
        ["ARTH 332"]
      ],
      [
        ["HIST 364", "HIST 365"]
      ]
    ]
    
    let x = [
      [
        ["BUS 300"]
      ],
      [
        ["BUS 310"]
      ],
      [
        ["BUS 330"]
      ],
      [
        ["MKT 300"]
      ],
      [
        ["ACCT 301"]
      ],
      [
        ["MGMT 362"]
      ],
      [
        ["BUS 345"],
        ["BUS 340"]
      ]
    ];
    
    let z = [
        [
        ["BUS 300"]
      ],
      [
        ["BUS 310"]
      ],
      [
        ["BUS 330"]
      ],
      [
        ["MKT 300"]
      ],
      [
        ["ACCT 301"]
      ],
      [
        ["MGMT 362"]
      ],
      [
        ["BUS 345"],
        ["BUS 340","BUS 340"]
      ]
    ]
        
    function transform(a) {
      let length = a.length;
      let result = [];
      for (let i = 0; i < length; i++) {
        if (a[i].length > 1) {
          result.push(
            a[i].map(e=>e.join(" and ")).join(" or ")
          )
        } else if (a[i][0].length > 1) {
          result.push(a[i][0].join(" and "))
        } else {
          result.push(a[i][0]);
        }
      }
      return result.join(" / ");
    }
    
    console.log(transform(y));
    console.log(transform(x));
    console.log(transform(z));