user12558800
user12558800

Reputation: 13

Javascript array.some: pass params to callback

I learned about array.some() and want to use it for a check if an object property is already set for any object in an array.

But I cannot get it working. I dont know how to pass the params to the callback function.

function hasPropertyValue(obj, property, value){
    return (obj[property] === value);
}

let arr = [
    { id: 1, name: 'Name1'},
    { id: 2, name: 'Name2'}
];

console.log(arr.some(hasPropertyValue(element, 'id', 1)));   //Uncaught ReferenceError: element is not defined

Upvotes: 1

Views: 494

Answers (4)

Gopinath
Gopinath

Reputation: 4937

array.some() method checks if at least one element in the array matches a condition defined in a 'validator function'.

It requires only the name of the validator function as the parameter. Best practice is to use the validator function without arguments.

Here is a fix for the above mentioned problem:

// File name: array_some_demo.js

function hasPropertyValue(array_element) {
    // Verify if the 'id' attribute of the element is 1
    return (array_element.id === 1)
}

let arr = [
    { id: 100, name: 'Name100'},
    { id: 1, name: 'Name1'},
    { id: 2, name: 'Name2'}
]


//  Call the .some method with 'hasPropertyValue' as the parameter.
//  This will initiate a loop of hasPropertyValue on all elements.
// 
//  Execution breaks out of the loop 
//  when an element with 'id' value of 1 is found.

console.log(arr.some(hasPropertyValue))

Output:

$ node array_some_demo.js

true

Upvotes: 0

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

By doing arr.some(hasPropertyValue(element, 'id', 1)) you pass the result of calling hasPropertyValue to .some, instead you want to pass the function itself to it. That could be done with arr.some(hasPropertyValue), but the arguments of .some do not match the parameters of hasPropertyValue. So you need to pass a function, that then calls your function:

function hasPropertyValue(obj, property, value){
    return (obj[property] === value);
}

let arr = [
    { id: 1, name: 'Name1'},
    { id: 2, name: 'Name2'}
];

console.log(arr.some(element => hasPropertyValue(element, 'id', 1)));

Upvotes: 1

James
James

Reputation: 22237

The thing inside array.some needs to be a function, not the result of a function call. ie

arr.some(element => hasPropertyValue(element, 'id', 1));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could take a closure over the wanted key and value and return a function which gets the object from the calling method.

function hasPropertyValue(property, value) {
    return function(object) {
        return (object[property] === value);
    };
}

let arr = [{ id: 1, name: 'Name1' }, { id: 2, name: 'Name2' }];

console.log(arr.some(hasPropertyValue('id', 1)));

Upvotes: 1

Related Questions