-2

I'm running this function to flatten an array:

function flatten(array) {
  return array.join(',').split(',');
}

array = [[1,2,3],[1,2,3]];
alert(flatten(array));

it's working in the below snippet but when I try to use it in the site codewars, I get '\' inserted at each character, causing the test to fail. Why is that?

This is the output:

Time: 496ms Passed: 0 Failed: 78
Test Results:
  Basic tests
✘ Expected: '[]', instead got: '[\'\']'
✘ Expected: '[]', instead got: '[\'\', \'\']'
✘ Expected: '[1]', instead got: '[\'\', \'1\']'
✘ Expected: '[1, 2]', instead got: '[\'\', \'\', \'\', \'2\', \'\', \'1\']'
✘ Expected: '[1, 2, 3, 4, 5, 6, 7, 8, 9]', instead got: '[\'3\', \'2\', \'1\', \'7\', \'9\', \'8\', \'6\', \'4\', \'5\']'
✘ Expected: '[1, 2, 3, 4, 5, 6, 100]', instead got: '[\'1\', \'3\', \'5\', \'100\', \'2\', \'4\', \'6\']'
✘ Expected: '[111, 222, 333, 444, 555, 666, 777, 888, 999]', instead got: '[\'111\', \'999\', \'222\', \'333\', \'444\', \'888\', \'777\', \'666\', \'555\']'
 Completed in 7ms

These are the tests:

describe("Example test cases", function() {
  Test.assertSimilar(flattenAndSort([]), []);
  Test.assertSimilar(flattenAndSort([[], [1]]), [1]);
  Test.assertSimilar(flattenAndSort([[3, 2, 1], [7, 9, 8], [6, 4, 5]]), [1, 2, 3, 4, 5, 6, 7, 8, 9]);
  Test.assertSimilar(flattenAndSort([[1, 3, 5], [100], [2, 4, 6]]), [1, 2, 3, 4, 5, 6, 100]);
});
Norman Chan
  • 476
  • 4
  • 17
  • Are you asking about the [proper way to flatten a multidimensional array](http://stackoverflow.com/q/27266550/5743988)? Or are you just asking about the slash being inserted? – 4castle Dec 30 '16 at 23:43
  • just the slash being inserted. I've already implemented the correct solution. @4castle – Norman Chan Dec 30 '16 at 23:45
  • 1
    You may want to edit your question so that it shows what codewars shows. – 4castle Dec 30 '16 at 23:50

1 Answers1

0

You can use Array.prototype.concat()

var array = [[1,2,3], [1,2,3]];

var result = array[0].concat(array[1]);

console.log(result);

Your function in converting numbers to string so the result is an array of strings:

function flatten(array) {
  return array.join(',').split(',');
}

var array = [[1,2,3],[1,2,3]];

console.log(flatten(array));

Backslashes are inserted to escape single quotes - for some reason the text is displayed as a JavaScript string with escape sequences.

Damian
  • 2,752
  • 1
  • 29
  • 28