'How to return a string with quotes on output [duplicate]

I wrote this code:

function unusedDigits(numbers) {
    let s = numbers.join('');
    let arr = s.split('');
    let ch = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let arraRes = [];


    for (let i = 0; i < ch.length; i++){
        if (!arr.includes(ch[i])) {
           arraRes += ch[i];
        }
    }

    return String(arraRes); // also tried return arraRes + "";
}

console.log(unusedDigits([12, 34, 56, 78])); //09
console.log(unusedDigits([2015, 8, 26]));  //3479

But I can't understand why a number on output. I need on output numbers with quotes - "09" and "3479"



Solution 1:[1]

The following line:

arraRes += ch[i];

Converts the array into a string. You should use push() to add stuff to an array. This way the array is preserved and you're getting an array of string as return


function unusedDigits(numbers) {
    let s = numbers.join('');
    let arr = s.split('');
    let ch = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let arraRes = [];


    for (let i = 0; i < ch.length; i++){
        if (!arr.includes(ch[i])) {
           arraRes.push(ch[i]);
        }
    }

    return arraRes;
}

console.log(unusedDigits([12, 34, 56, 78])); //09
console.log(unusedDigits([2015, 8, 26]));  //3479

Solution 2:[2]

Two possible ways:

Example with string simple concat

function unusedDigits(numbers) {
    let s = numbers.join('');
    let arr = s.split('');
    let ch = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];    
    let strRes= '';

    for (let i = 0; i < ch.length; i++){
        if (!arr.includes(ch[i])) {           
           strRes += ch[i] + ', ';
        }
    }
        return strRes;    
}

console.log(unusedDigits([12, 34, 56, 78])); //09
console.log(unusedDigits([2015, 8, 26]));  //3479

Example with array

function unusedDigits(numbers) {
    let s = numbers.join('');
    let arr = s.split('');
    let ch = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    let arraRes = [];

    for (let i = 0; i < ch.length; i++){
        if (!arr.includes(ch[i])) {
           arraRes.push(ch[i]);
        }
    }

    return String(arraRes); // also tried return arraRes + "";
}

console.log(unusedDigits([12, 34, 56, 78])); //09
console.log(unusedDigits([2015, 8, 26]));  //3479

Conclusion: I would prefer the first one because you dont need to cast the array back to an string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 0stone0
Solution 2 Maik Lowrey