Match the Array and Array with Dictionary using Javascript

on

“fruits” is an array variable. It contains 4 fruits name.
“list” is an array variable but contains the 4 number of dictionary.

Checking whether a value exists in an array or not which using below code to achieve this.

var fruits = ['apple', 'banana', 'mango', 'guava'];
var list = [
      {name:'apple', category: "fruit", price: 1.22 },
      {name:'pear', category: "fruit", price: 2.22 },
      {name:'coke', category: "drink", price: 3.33 },
     {name:'sprite', category: "drink", price: .44 },
    ];
    
function checkArray(arr, val) {
    return arr.some(function(arrVal) {
        return val === arrVal['name'];
    });
}

function checkArrayWithDictionary(arr, val) {
    return arr.some(function(arrVal) {
        return val === arrVal['name'];
    });
}

checkArray(fruits, 'kela'); //false
document.body.innerHTML = checkArray(fruits, 'banana'); //true
document.body.innerHTML = checkArrayWithDictionary(list, 'apple'); //true

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s