I have an array of similar objects like this:
const urls = [
{
title: "title 1",
url: "https://example.com/1"
},
{
title: "title 2",
url: "https://example.com/2"
},
...
]
To reduce the repetition, I think of making a class:
class URL {
title: string
url: string
constructor(title:string, url:string) {
this.title = title
this.url = url
}
}
const link1 = new URL("title 1", "https://example.com/1")
const link2 = new URL("title 2", "https://example.com/2")
This has 2 cons:
- I have to assign unused variable names
- Create an array of them seem to lead to memory leak
Is there a better way? My goal is to run a filter on the array (input a specific title
, output its corresponding url
).
2
Answers
From what you describe what you actually want is just a lookup using a title to obtain a URL.
You should not be using arrays for this at all (at least for a larger amount of URLs). Best to use a
Map
or a JS object since those are designed for lookups and can therefore do them very fast i. e. sub-linear.From the MDN docs:
With JavaScript object
With a
Map
Lookup URL by titles following a specific pattern
If your titles follow a specific pattern and you want to be smart about things and not waste storage unnecessarily you could also do something like the following:
Here a very simple example based on your example. Depending on the complexity of your title and your URLs this can get much more complex.
If your goal is to filter the array based on the title and retrieve the corresponding URL, you can achieve it without creating instances of a class. You can use an object or a Map to store the titles as keys and their corresponding URLs as values. Here’s how you can do it:
In this approach:
urls
).getUrlByTitle
function takes a title as input and returns the corresponding URL from theurls
object.urls
object, it returns the corresponding URL; otherwise, it returnsnull
.This approach eliminates the need to create instances of a class and avoids memory overhead. It also simplifies the code and makes it more concise.