M
M
max_bu2017-08-29 20:29:18
JavaScript
max_bu, 2017-08-29 20:29:18

How to properly process array data? .filter() method?

Hello, please tell me:
Task:
1. There is an associative array with such objects: (we are talking about hundreds of such objects inside)

arr: [ { name: ' SB ', id: 'O5', value: 10,}, { name: ' SB ', id 'O5', value: 11,} ]

2. I accept the value from the select in 2Vue.js:
options: [{
            value: 'O1',
            label: 'Первый'
            },{
            value: 'O7',
            label: 'Второй'
            }]

3. It is necessary to check each array object for compliance with the selected select value.
4. Output those objects that fall under this condition into a new array
5. Find an object in a new array with a minimum value
I clumsily did this:
RSUM: function (){
          var response = this.arr;
          var va = this.value;
          var defaul = this.defaultPrograms;
          var rates = response.filter(function(elem) {
            return elem.id == va;
            });
            if (rates.length == 0) {
                rates = defaul;
                console.log(rates);
                };
                console.log(rates.length);
                var minEl = rates[0].value
                var br = rates.filter(function(elem){
              return elem.value <= minEl;
          });
            
          console.log(br);
          this.ValueMin = br[0].value;
        console.log(this.ValueMin);
      }

But it works every other time, and I feel that it works by chance.
QUESTION ONE: How to implement this functionality correctly and better? (assuming more than 100 data)
QUESTION TWO: If multiple items have minimum values, how do I add a second ranking parameter?
QUESTION THREE: How to do the same filtering by several parameters? For example, add to a new array when it matches: id/(checkbox1)/(checkbox) and so on...
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Danila, 2017-08-29
@Machinez

why did you decide that the first element will be minimal? here we need a sort method rather than a filter

var br = rates.filter(function(elem){
     return elem.value <= minEl;
});

similar to the first question, you filtered the array by the value of the first element, this does not mean that the first element of the new array will be minimal. if there is more than 100 data, then it is better to do filtering and sorting in one pass through the array
var rates = response.reduce(function (acc, elem) {
    if (elem.id === va) {
      if (!acc) {
        return elem.value;
      }
      
      return elem.value < acc ? elem.value : acc;
    }

    return acc;
}, 0);

corrected the code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question