0

I'm attempting to return two arrays(multiple values) through declaring them as objects



<script>
    function funWithArrays(arr) {

        const arr1 = []; //short string
        const arr2 = []; //long string

        for (var i = 0; i < arr.length; i++) {
            if (arr[i].length <= 3) {
                arr1.push(arr[i]);
            } else {
                arr2.push(arr[i]);
            }
        }
        return {
            arr1,
            arr2
        };

    }
    document.getElementById("results").innerHTML = funWithArrays(["we", "cream", "to", "this", "two"]);

</script>

This is my attempt to do so, however, when I go to run it the output is as follows:

[object Object]

I'm wondering why the actual arrays aren't being returned?

2
  • 2
    You're not returning an array, you're returning a non-array object with the properties arr1 and arr2 (those props refer to arrays). Then you're implicitly converting that object to string by assigning it to innerHTML, which triggers the default toString for objects (since yours doesn't define one), which for plain objects returns the string "[object Object]". If you wanted to return an array of arrays, it would be return [arr1, arr2]; (square brackets), which would convert to a string containing the string version of the array elements (but a bit confusingly, for nested arrays). Commented Nov 1, 2021 at 7:29
  • By "confusingly," I mean: The array [ [1, 2, 3], [4, 5, 6] ] converts to the string "1,2,3,4,5,6" (which is exactly what [1, 2, 3, 4, 5, 6] would convert to). Commented Nov 1, 2021 at 7:32

1 Answer 1

0

You are returning incorrectly.

replace return {arr1, arr2} with return [...arr1, ...arr2] to return a single array.

Wrapping arrays in curly brackets( { } ) convert them into an object. Since you need to return an array, wrap your arrays in square brackets( [ ] ) instead.

documentation for Spread Operator

Sign up to request clarification or add additional context in comments.

2 Comments

um I dont know if I can ask this but this was part of a practice question for my exams part of it was asking for this "the function should return an object which has two properties both arrays and named as arr1 and arr2, respectively" is this still correct?
@user16973340 - Your original code was doing what that sentence requests; the code above does not. So it may just be that you need to format your output, not change your return value. For instance, you could show the result as JSON: .innerHTML = JSON.stringify(funWithArrays(/*...*/)); (but that's just one possible way you could format it).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.