F
F
fh2017-11-08 20:08:48
JavaScript
fh, 2017-11-08 20:08:48

Sorting an array of data into groups/collections?

I have an array of data, let's say this (JSON) :

[
  {
    name: Apple
  },
  {
    name: Orange
  },
  {
    name: Tomato
  }
]

And I want to create new lists (collections, groups) , let's say "fruits" and "vegetables". But at the same time, so that the initial list also exists, it will be called "All". How can I do it better? How will it be faster, more optimized in order to then view these collections?
I have two options in mind: 1) create new arrays (a separate array for each collection) and simply duplicate the data there
2) Give properties to each of the elements of the "collection: fruit" type for the first element, and then simply go through to display the entire collection the entire array and match the collection name to display it.
Do you have options? I think 1 sucks because it needs to be duplicated, and 2 sucks because if there are a lot of elements in general,

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2017-11-08
@ThunderCat

without a specific applied task, the question boils down to "which is better - tomatoes or apples?". Each decision has a degree of expediency, for example "it will be requested more often in format A than in format B, so we store format A, if necessary, reshape it into B". How to implement in each case should be decided by the one who will use it in the code, based on common sense.

A
Alexander Skusnov, 2017-11-08
@AlexSku

The collection option is good. Only, since you have databases, you don't need to make passes: just organize the tables and make a SQL query.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question