1
In this example I already have the numbers of indexes of elements within an Array, but with these numbers I need to get the information out of the Main Array.
This amount of indexes is variable, so it can change at any time.
IndexNumbers = [ 0, 2 ] // posição das informações na Array
Main Array, from where I need to get the information from the indexes:
Array= [
{name: "Teste 3", amount: 15000, day: 17},
{name: "Teste 1", amount: 80000, day: 10},
{name: "Teste 1", amount: 800000, day: 17}
]
I tried to use the method slice()
since it does not alter the Array Principal, but I couldn’t apply it in a way that was what I needed!
The desired return would have to be:
SliceReturn = [
{name: "Teste 3", amount: 15000, day: 17},
{name: "Teste 1", amount: 800000, day: 17}
]
Since JS is not one of those languages that throw an exception when trying to index an element that does not exist, I think that would simplify the conditional expression:
if (array[posicao]) { ... }
.– Luiz Felipe
@Luizfelipe In the case of the array of the question yes, but in a more general case, and if the array has elements like the empty string, the zero number, or even
null
/undefined
? Then it would make a difference... :-)– hkotsubo
In this case (probably) it wouldn’t even be worth including them in the new array in most situations, but strictly speaking, it’s true.
– Luiz Felipe
@Luizfelipe "nor would it be worth including them" - There’s no way of knowing, every case is a case. If the only criterion is "copy the elements of these positions" (regardless of the value), it is better to use what I did. If the criterion is different, then we change the
if
, may even be what you suggested :-)– hkotsubo
Absolutely! But I’m talking about the case of that question, because if you had a
null
,undefined
(or any other value than object), the AP would have a Runtime error (cannot access Property of Undefined and similar) elsewhere in the application, unless it always does the proper checking before using the array (which we know is not the case most of the time). Anyway, for general cases, what’s in the answer really is "better", it was just a suggestion for this case. :-)– Luiz Felipe
this question was closed but I honestly did not find "outside the scope"
– Ricardo Pontual