Home > front end >  In JavaScript, how can I update each element of an array the same way without using a loop?
In JavaScript, how can I update each element of an array the same way without using a loop?

Time:02-10

For example, if I have an array:

movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]

How do I turn the movies array into

[{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}]

without using a loop? Is it possible to do it in O(1)?

In the same way, If I have an integer array and need to increment every element by one, can I do it without a loop?

CodePudding user response:

It is impossible.

If your input set contains N elements, you cannot create a different structure of N other elements without a loop. Any algorithm that isn't hard-coded to the input array will require an O(n) loop.

The only (cheating) O(1) approach would be something like

const transformMovies = () => [{title: "Spider Man"}, {title: "Avatar"}, {title: "Titantic"}, {title:"Avengers"}];

which of course only works for one possible input, and not for the general problem.

  •  Tags:  
  • Related