-1

As I understood there is no best practice for copying an Array in Javascript.

Would it be a could idea to use Array.filter, to copy an Array?

Something like:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word);

Because filter returns a new Array? Are there any disatvantages using this Method?

simplesystems
  • 839
  • 2
  • 14
  • 28
  • if you want a copy of the original array with only words whose length are greater than 6, then yes, that is the best way of doing it – Jaromanda X Jul 23 '18 at 09:17
  • 2
    Possible duplicate of [Javascript fastest way to duplicate an Array - slice vs for loop](https://stackoverflow.com/questions/3978492/javascript-fastest-way-to-duplicate-an-array-slice-vs-for-loop) – Colin Jul 23 '18 at 09:18
  • 1
    but slice vs loop is irrelevant when you filter @Colin – Jaromanda X Jul 23 '18 at 09:18
  • sorry I edited the filter function, no length restriction – simplesystems Jul 23 '18 at 09:36

1 Answers1

3

IMHO, you are looking for something like this:

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

var wordsCopy = Array.from(words);

console.log(wordsCopy);
BlackBeard
  • 10,246
  • 7
  • 52
  • 62