Reputation: 496
I would like to use the $.each()
loop to iterate over digits in an integer.
The integer is produced as the index of another array, though I'm not sure that this makes a difference.
Javascript
var words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
var numbers = [];
$.each(words, function(i,word) {
$.each(i, function(index,value) {
$(numbers).append(value);
});
});
I would like the array numbers
to equal the following array:
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1 ]
Where the last four entries, [ ... 1, 0, 1, 1 ]
are generated through iteration over the indexes for the entries [ ... "than", "ten." ]
in the words
array.
Upvotes: 0
Views: 2313
Reputation: 350270
The words themselves play no role in the output, so the input really is only the length. You could use the flatMap
iterator helper here:
// The input really is only a length:
const n = 12;
const digits = n => Array.from(n+"", Number);
const numbers = Array(n).keys().flatMap(digits).toArray();
console.log(...numbers);
Upvotes: 0
Reputation: 14423
let words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
let numbers = words.map((w, i) => i.toString().split('').map(Number)) //map into array of digits
numbers = Array.prototype.concat.call(...numbers); //concat them all
console.log(numbers);
Upvotes: 2