0

This is more like a silly question but I have to ask it. It is a good practice to call an array function like map without arguments? Let's say I already have an array 'x' on my code with a specified length and I want to make another array with the same length but with different content. For example:

function generateRandomContent() { ... }
const x = [1, 2, 3, 4, 5]
const y = x.map(() => generateRandomContent())
// or
const z = Array(x.length).fill().map(() => { ... })

Of course I could pass an argument and never use it, but it is there a good way and a bad way to do it?

8
  • 5
    Why would you want to do a mapping operation if it's not dependent on anything but the size of the initial array? Commented Dec 27, 2019 at 14:45
  • 1
    .map() is not supposed to be used without arguments. You could use .forEach() instead or a for loop. Commented Dec 27, 2019 at 14:45
  • 4
    Array.from({length: x.length}, () => someFn()) or even Array.from({length: x.length}, someFn) will generate an array as the same size with different contents. .map signifies that the content of the new array is closely related to the content of the original array. Commented Dec 27, 2019 at 14:47
  • Maybe it's worth considering Array.from, which takes a function as its second argument. E.g.: Array.from(Array(10), generateRandomContent). Commented Dec 27, 2019 at 14:48
  • 3
    @Yousername forEach makes even less sense there. Commented Dec 27, 2019 at 14:50

1 Answer 1

1

You should not use .map here. A mapping operation is when you take some input and generate a new output. So you have a relation that looks like this x -> y for a single element, then you apply it to the entire array to generate a new array using the same mapping rule:

const input = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];

//mapping relationship
const toCharacter = x => String.fromCharCode(x);

const result = input.map(toCharacter);

console.log(result.join(''))

If you just want to create a new array based on the length of the original but with totally unrelated content, then you are better off to use Array.from which can create an array with a given size and takes a second argument that will fill it with content:

function generateRandomContent() {
  return Math.floor(Math.random() * 100);
}
const x = [1, 2, 3, 4, 5]

const y = Array.from({length: x.length}, () => generateRandomContent());
//or just pass the function reference
const z = Array.from({length: x.length}, generateRandomContent);


console.log(y);
console.log(z);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.