Sachin
Sachin

Reputation: 155

How to filters two arrays with multiple keys and value?

var filteredKeyItems = ['primary','gender','regular','normal']
var filteredValuesItems = ['genreal','M',true]

// Output should be:

filteredKeyItems = ['primary','gender']
filteredValuesItems = ['genreal','M']

Here there is a snippet of the two arrays with the keys and values. How can I filter multiple keys as denoted into the code regular and normal with values true in values arrays. Final output should be as per the denoted into the snippet.

Thanks.

Upvotes: 0

Views: 498

Answers (2)

wrager
wrager

Reputation: 872

The beauty functional way is:

var filteredKeyItems = ['primary','gender','regular','normal']
var filteredValuesItems = ['genreal','M',true]

function filterKeyItem(keyItem) {
    return keyItem !== 'regular' && keyItem !== 'normal';
}

filteredValuesItems = filteredValuesItems.filter((valueItem, index) => filterKeyItem(filteredKeyItems[index]));
filteredKeyItems = filteredKeyItems.filter(filterKeyItem);

console.log('filteredKeyItems', filteredKeyItems);
console.log('filteredValuesItems', filteredValuesItems);

To improve performance a bit, you can use a simple for loop with filling result arrays.

Upvotes: 0

akshay bagade
akshay bagade

Reputation: 1219

we can do this also by follow

    var filteredKeyItems = ['primary','gender','regular','normal']
    var filteredValuesItems = ['genreal','M',true]


    let filterTwo=[]
    let filterOne=filteredKeyItems.filter((element,index)=>{
     
      //we can assign condition here
    if(element=="primary" || element=="gender" ){
       filterTwo.push(filteredValuesItems[index])
      return  element}}  )
   
    console.log(filterOne)
    console.log(filterTwo)

Upvotes: 1

Related Questions