Earlier I’ve written an article on how you can populate an array with numbers in JavaScript. Here in this article we’re learn how we can populate an array with random words without using any additional library.
Sometimes during testing a front-end feature, we might need some dummy data. This data might be in the form of numbers, list of words or list of objects. Let’s have a look at how we can define a list of words with length N.
Initially, we could define a few words, and then we could pick them up randomly to generate a long list of words.
function createWord() {
return 'Gautam Nina John Lin Casey Peter'.split(' ')[
Math.floor(Math.random() * 6)
]
}
const words = Array(10)
.fill()
.map((_, i) => `${createWord(i)}${i}`)
words && console.log(words)
//output
[
'Lin0', 'Peter1',
'Nina2', 'Casey3',
'Lin4', 'Gautam5',
'Nina6', 'Casey7',
'Lin8', 'Nina9'
]
Code language: JavaScript (javascript)
In the code above, we’re filling an array by passing an index to the createWord method. This method picks up a random name from the list of six names. We then append the index i to the name to make it unique.
Of course, we can modify the code further to have it return a list of objects instead:
function createObject(index) {
const names = 'Gautam Nina John Lin Casey Peter'.split(' ')
return {
id: index,
title: (names[Math.floor(Math.random() * 6)] + index).toString(),
}
}
const words = Array(10)
.fill()
.map((_, i) => createObject(i))
words && console.log(words)
//output
[
{ id: 0, title: 'Gautam0' },
{ id: 1, title: 'Nina1' },
{ id: 2, title: 'Casey2' },
{ id: 3, title: 'Gautam3' },
{ id: 4, title: 'Peter4' },
{ id: 5, title: 'John5' },
{ id: 6, title: 'Peter6' },
{ id: 7, title: 'Peter7' },
{ id: 8, title: 'John8' },
{ id: 9, title: 'Casey9' }
]
Code language: JavaScript (javascript)
In the code above, we’re creating an object using the createObject method. It simply takes in an index number and uses it as an id for the object. Along with the number appended to the randomly picked name for title.