John Paine
John Paine

Reputation: 63

Testing multidimensional arrays in javascript

I solve challenges on FreeCodeCamp. Code below passes their tests and challenge marked as resolved but my own tests don't pass and I just don't get why...

function chunk(arr, size) {
    if (size >= arr.length || size <= 0)
        return [arr];
    var result = [];
    var i = 0;
    while(arr.length > 0) {
        result.push([]);
        for (var j = 0; j < size && arr.length > 0; ++j) {
            result[i].push(arr.shift());
        }
        i++;
    }
    return result;
}

alert(chunk(["a", "b", "c", "d"], 2) == [["a", "b"], ["c", "d"]]);

Alert should print true if I got the essense of arrays in JS right, but it prints false and I don't know why?

Upvotes: 1

Views: 100

Answers (2)

John Slegers
John Slegers

Reputation: 47101

This is the most efficient solution :

function chunk(arr, size) {
    var output = [];
    var length = arr.length;
    for (var x = 0, length = arr.length; x < length; x = x + size) {
        output.push(arr.slice([x], x + size));
    }
    return output;
}

var array1 = chunk(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M'], 2);

var array2 = [
    ["A", "B"],
    ["C", "D"],
    ["E", "F"],
    ["G", "H"],
    ["J", "K"],
    ["L", "M"]
]

var equals = (array1.length == array2.length) && array1.every(function(element, index) {
  return (element.length == array2[index].length) && element.every(function(element1, index1) {
    return element1 === array2[index][index1];
  });
});
alert(equals);

Upvotes: 0

P. Jairaj
P. Jairaj

Reputation: 1033

This is working:

function chunk(arr, size) {
  if (size >= arr.length || size <= 0)
    return [arr];
  var result = [];
  var i = 0;
  while (arr.length > 0) {
    result.push([]);
    for (var j = 0; j < size && arr.length > 0; ++j) {
      result[i].push(arr.shift());
    }
    i++;
  }
  return result;
}
var array1 = chunk(["a", "b", "c", "d"], 2);
var array2 = [
  ["a", "b"],
  ["c", "d"]
];
var equals = (array1.length == array2.length) && array1.every(function(element, index) {
  return (element.length == array2[index].length) && element.every(function(element1, index1) {
    return element1 === array2[index][index1];
  });
});
alert(equals);

More info: How to Compare two Arrays are Equal using Javascript?

Upvotes: 1

Related Questions