7

What would be the time complexity of Array.from(). For example:

const set = new Set();
set.add('car');
set.add('cat');
set.add('dog');

console.log(Array.from(set)); // time complexity of making this convertion from Set to Array
3
  • Just the cost of iteration plus the cost of pushing to an array (O(n) on the length of the result), so O(n) for a Set. Commented Dec 4, 2019 at 9:46
  • Why do you ask? Array.from() has a different "problem"; it's quite slow compared to other methods to create that Array. This seems to be due to the overhead generated by the wide variety of input types that the method may have to deal with. So for small data-structures this overhead may outweigh the execution time of the actual task at hand. Commented Dec 4, 2019 at 9:51
  • Sharing this may be useful for someone, we can return array like this also const newArr= [...new Set(arr)];no need to always write Array.from(set) Commented May 12, 2022 at 19:23

2 Answers 2

6

It's O(n). When used on an iterable (like a Set), Array.from iterates over the iterable and puts every item returned into the new array, so there's an operation for every item returned by the iterable.

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

3 Comments

That doesn't necessarily mean that it's O(n) though. The time complexity depends on the internal implementation so it could be O(n log n) if internally it uses something like Array.prototype.push to add elements to the returned array. That would be a stupid way to implement that, but until I see otherwise I am assuming the worst. And that would also explain why it is so slow.
Personally, I feel safe assuming that, when the amount of data is large enough for complexity to have any visible effect, the writers of the various modern JS engines do not choose to use a stupidly inefficient algorithm. It wouldn't be theoretically impossible for someone to go with such an algorithm, but it would be an extremely odd decision to make (except when weird edge cases are involved, in which case all bets are off anyway)
I'm fairly certain now that the time complexity is indeed O(n log n) because I did a benchmark and it's no faster using Array.from() than it is to just create an array of size 0 and then call Array.prototype.push on it 16 million times. Here's to hoping this gets fixed in future releases of JavaScript.
1

It is always going to be O(n) as the number of iterations would be directly proportional to the number of elements in the set. Actual Time complexity would be O(n) for retrieving values from a set O(n) for pushing into an array.

O(n) + O(n) = O(2n)

But since we do not consider a constant value when calculating using n value it should be O(n).

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.