Convert Array to List of Selectors

Viewed 145

need a help with converting array, for example "01b,02b,03c" to a list of selectors "#01b,#02b,#03c which I can use as list of selectors in the jQuery

HTML

<input type="radio" id="01b"/>
<input type="radio" id="02b"/>
<input type="radio" id="03c"/>

JavaScript

var arr = ['01b','02b','03c'];
// var newArr = would be a list of selectors, like ['#01b','#02b','#03c'];

// then I would use it in the JavaScript to pre-check radio buttons
$(newArr).prop('checked', true);

So output would be like

<input type="radio" id="01b" checked="checked"/>
<input type="radio" id="02b" checked="checked"/>
<input type="radio" id="03c" checked="checked"/>

I have tried to use something like

var newArr = arr.each(function() {
 return '#'+ $(this);
});

But it seems to be far from valid;

2 Answers

arr.each don't return the result back. So, the newArr in you're example is undefined.

You can use arr.map, which creates the new array of mapped elemenents and returns it back.

const newArr = arr.map(function(el) {
    return '#' + el
})

You can use map() to convert the array of strings from one format to another. Also note that you will need to call join() to serialise the array back to a string with comma separators for it to be recognised in the jQuery object:

var arr = ['01b', '02b', '03c'];
let selector = arr.map(s => `#${s}`).join(',');
$(selector).prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="01b" />
<input type="radio" id="02b" />
<input type="radio" id="03c" />

Alternatively, you can simply use a class.

Related