-4

So I have a array which I want to filter but dont know how to do it. I am getting a value of sector title in params and it can be one value or list of different values on the basis of which I want to filter

var params = "WOOLEN"
var arr =  
    [{
        "sector_title": "WOOLEN",
        "sector_rate": "44",
    }, {
        "sector_title": "GLASS",
        "sector_rate": "31",
    }, {
        "sector_title": "PALM",
        "sector_rate": "34",
    }]
jabaa
  • 5,844
  • 3
  • 9
  • 30

2 Answers2

-1

You can use filter or find function according to your purpose.

filter: Returns all item that meet the condition.

find: Return first item that meet the condition.

var params = "WOOLEN";
var arr = [{
            "sector_title": "WOOLEN",
            "sector_rate": "44",
        }, {
            "sector_title": "GLASS",
            "sector_rate": "31",
        }, {
            "sector_title": "PALM",
            "sector_rate": "34",
        }];
        
  var allResults = arr.filter(item => item.sector_title === params);
  
  console.log(allResults);
  
  var firstResult = arr.find(item => item.sector_title === params);
  console.log(firstResult);

For multiple condition and values you can use && (and) or || (or) operators.

function filterData(params){
  var complexQueryResult = arr.filter(
  (item) =>
    // sector title is not defined or sector title contains item's sector title
    (!params.sector_title || params.sector_title.indexOf(item.sector_title) > -1) &&
    // sector rate is not defined or sector rate contains item's sector rate.
    (!params.sector_rate || params.sector_rate.indexOf(item.sector_rate) > -1)
);
console.log(complexQueryResult);
return complexQueryResult;
}

// Filter for sector_title is 'WOOLEN' or 'GLASS' and sector_rate is '44' or '31'
filterData({
  sector_title: ['WOOLEN', 'GLASS'],
  sector_rate: ['44', '31'],
});
// Output: [ { sector_title: 'WOOLEN', sector_rate: '44' }, { sector_title: 'GLASS', sector_rate: '31' } ]


// Filter for sector_title is 'WOOLEN' and sector_rate is '44'
filterData({
    sector_title: ['WOOLEN'],
   sector_rate: ['44'],
});
// Output:  [ { sector_title: 'WOOLEN', sector_rate: '44' } ];


// Filter for sector_title is 'GLASS'
filterData({
  sector_title: ['GLASS']
});
// Output [ { sector_title: 'WOOLEN', sector_rate: '44' }]
ierhalim
  • 298
  • 3
  • 16
-1

You can use indexOf

var arr = [
  {
    "sector_title": "WOOLEN",
    "sector_rate": "44",
  }, {
    "sector_title": "GLASS",
    "sector_rate": "31",
  }, {
    "sector_title": "PALM",
    "sector_rate": "34",
  }
];


function findByTitle(query) {
  return arr.filter(x => x.sector_title.toLowerCase().indexOf(query.toLowerCase()) !== -1);
}


console.log(findByTitle('WOOLEN'));
console.log(findByTitle('PA'));
jabaa
  • 5,844
  • 3
  • 9
  • 30