Javascript Data Type How to - Check if a value is contained within an Array








Question

We would like to know how to check if a value is contained within an Array.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- www.j  ava 2s .c o  m-->
var objs = [{name: 'foo', path: 'c:/a'}, {name: 'foo', path: 'c:/b'}];

var conditionallyAddObjToArr = function (arr, obj) { 
    if (!arr.some(function (_obj) { return obj.path === _obj.path; })) {
        return [].concat(arr, obj);
    } else {
        document.writeln('path is already present', obj.path)
        document.writeln('<br/>');
        return arr;
    }
}
objs = conditionallyAddObjToArr(objs, {name: 'baz', path: 'c:/c'})
objs = conditionallyAddObjToArr(objs, {name: 'baz', path: 'c:/c'})
document.writeln(JSON.stringify(objs));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: