user7784271
user7784271

Reputation:

How to use map function instead of for loop in javascript?

This is my array :

var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]

I use for loop

for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}

How to exactly do this with map ? in javascript instead of for loop.

Upvotes: 5

Views: 5246

Answers (4)

Rahul Patidar
Rahul Patidar

Reputation: 1

var filteredData = [{ id: 1, phoneno: '77777777777', sender: 'test' },{ id: 2, phoneno: '917338966917', sender: 'hel' }]
filteredData.map(filterDetails); 
function filterDetails(data) {  
    if(data.sender == 'test'){
     console.log('worked');
     }
     else{
     console.log('not worked');
     }
}

Upvotes: -3

Giovanni Lobitos
Giovanni Lobitos

Reputation: 852

As mentioned in the comments, forEach is better to be used in your example. But if you insist in using map, just replace forEach with map and the code would still work.

var filteredData = [{ id: 1, phoneno: '918888888888', sender: 'test' },{ id: 2, phoneno: '918888888888', sender: 'hel' }];

filteredData.forEach(function(item){
   if (item.sender === test) {
       console.log('worked');
   }
   else {
       console.log('not worked');
   }
});

Upvotes: 7

VijayVishnu
VijayVishnu

Reputation: 537

By using underscore.js,

var filteredData = [{ id: 1, phoneno: '917418306474', sender: 'test' },{ id: 2, phoneno: '917338966917', sender: 'hel' }];

 _.map(filteredData, function(data){
   if (data.sender === test) {
    console.log('worked');
   }else {
    console.log('not worked');}
});

Upvotes: -2

Nidhi Agarwal
Nidhi Agarwal

Reputation: 326

filteredData.map(value => {
    if (value.sender === test) {
        console.log("worked");
    } else {
        console.log('not worked');
    }
});

Upvotes: 0

Related Questions