Search code examples
javascriptalgorithmweblogic

Find repetition in Javascript 4 dimensional array


Sorry I misdescribed my problem :

If the argument value is "macOS" in the call like this -> countDuplicate(operatingSystem, "macOS");

The function must return the number of 9. The same for other values(Windows, Unix...).

Thank you !

let operatingSystem = [
  ["macOS", "Windows", "Unix"],
  ["macOS", ["Windows", "Unix", "macOS"], "Unix"],
  [["macOS", "Windows", "Unix"], "Windows", "Unix"],
  ["Unix", "macOS", ["Windows", "Unix", "macOS"]],
  [["macOS", "Windows", ["Unix", "Windows", "macOS"]], "Windows", "Unix"],
  [["Linux", "Android", ["Unix", "Windows", "macOS"]], "Windows", "Unix"],
];

function countDuplicate(array, arg) {
  let count = 0;

  for (let i = 0; i < operatingSystem.length; i++) {
    for (let j = 0; j < operatingSystem[i].length; j++) {
      for (let k = 0; k < operatingSystem[i][j].length; k++) {
        for (let l = 0; l < operatingSystem[i][j][k].length; l++) {
          let str = operatingSystem[i][j][k][l];
          if (str.indexOf(arg) > -1) {
            count += 1;
            break;
          }
        }
      }
    }
  }
  console.log("There is " + count + " of " + arg + " similar items in this array.");
}
countDuplicate(operatingSystem, "macOS");


Solution

  • This is a straightforward recursion. We can start with a list of values and a target, then scan through the values, adding to our running counter for each. If the value is an array, we recur on it with the same target. Otherwise if it matches the target, we add 1, and add nothing otherwise. It might look like this:

    const countDuplicate = (xs, t) => 
      xs .reduce ((c, x) => c + (Array .isArray (x) ? countDuplicate (x, t) : x == t ? 1 : 0), 0)
    
    const operatingSystem = [["macOS", "Windows", "Unix"], ["macOS", ["Windows", "Unix", "macOS"], "Unix"], [["macOS", "Windows", "Unix"], "Windows", "Unix"], ["Unix", "macOS", ["Windows", "Unix", "macOS"]], [["macOS", "Windows", ["Unix", "Windows", "macOS"]], "Windows", "Unix"], [["Linux", "Android", ["Unix", "Windows", "macOS"]], "Windows", "Unix"]];
    
    ['macOS', 'Windows', 'Unix', 'Linux', 'Android', 'Other'] .forEach (
      os => console .log (`${os}: ${countDuplicate (operatingSystem, os)}`)
    )