How I take information from within an Array from the index

Asked

Viewed 53 times

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}
    ] 

2 answers

4


You can get this by using a combination of filter, to filter array elements with some, to check if index is in the expected index list:

var indexes = [ 0, 2 ] // posição das informações na Array

var array= [ 
        {name: "Teste 3", amount: 15000, day: 17},
        {name: "Teste 1", amount: 80000, day: 10},
        {name: "Teste 1", amount: 800000, day: 17}
    ];

// o filter irá filtrar os elementos, baseado no .some, que vai identificar se contem algum ("some") elemento dos indexes esperados
var novoArray = array.filter((e,index) => indexes.some(i => index === i));

console.log(novoArray);

Another possibility would be to use the map(), mapping from array the items with the existing index in indexes:

var indexes = [ 0, 2 ] // posição das informações na Array

var array= [ 
        {name: "Teste 3", amount: 15000, day: 17},
        {name: "Teste 1", amount: 80000, day: 10},
        {name: "Teste 1", amount: 800000, day: 17}
    ];

var novoArray = indexes.map((item) => array[item])

console.log(novoArray);

Documentation of filter(), some() and map().

3

You don’t need slice. If you want another array, then... create another one, and add in it the elements you want.

In this case, just go through the array of positions and insert the respective element in the new array:

var posicoes = [ 0, 2 ]; // posição das informações na Array
var array = [
    { name: "Teste 3", amount: 15000, day: 17 },
    { name: "Teste 1", amount: 80000, day: 10 },
    { name: "Teste 1", amount: 800000, day: 17 }
];

var result = [];
for (var posicao of posicoes) { // para cada posição
    result.push(array[posicao]); // insere o elemento da posição
}

console.log(result);


A possible improvement is to check if the position actually exists in the array (because if you access a position that does not exist, a undefined in the final array):

var posicoes = [ 0, 2, 7 ]; // atenção, elemento na posição 7 não existe
var array = [
    { name: "Teste 3", amount: 15000, day: 17 },
    { name: "Teste 1", amount: 80000, day: 10 },
    { name: "Teste 1", amount: 800000, day: 17 }
];

var result = [];
for (var posicao of posicoes) {
    if (0 <= posicao && posicao < array.length) // verifica se o array possui a posição
        result.push(array[posicao]);
}

console.log(result);

  • 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]) { ... }.

  • @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... :-)

  • 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.

  • 1

    @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 :-)

  • 1

    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. :-)

  • this question was closed but I honestly did not find "outside the scope"

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.