'In JavaScript, how can I update each element of an array the same way without using a loop?
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?
Solution 1:[1]
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.
Solution 2:[2]
I would suggest regex, open to discussion on the complexity of the process
const movies = ["Spider Man", "Avatar", "Titantic", "Avengers"]
let moviesStr = JSON.stringify(movies); // O(1)
moviesStr = moviesStr.replace('["', '[{"title":"') // O(1)
moviesStr = moviesStr.replace('"]', '"}]') // O(1)
const regex = /,"/ig;
moviesStr = moviesStr.replaceAll(regex, '},{"title":"') // O(1) ???
const updateObj = JSON.parse(moviesStr);
console.log(updateObj)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
| Solution 2 | Dipak |
