0

When I try to use an arrow function with {} it seems to think it's an object and throw an error. I thought this is how arrow functions are generally defined?

The error given for the code below is TypeError: #<Object> is not a function

let allProperties = [];

sites.forEach(site => site.properties.forEach(p => {if (!allProperties.find(p)) allProperties.push(p)} ));

Edit: sites might be defined similarly to the following:

sites = [
{
    "properties": [
        { "id": "111-11", "display": "Zone", "value": 1 },
    ]
}];
8
  • 1
    What is sites? Please post a snippet which can reproduce your error. Commented Aug 19, 2016 at 22:11
  • If you use the {} with => you need to use the return statement. It only implicitly returns the value if you provide a single expression after =>, not if you provide a block Commented Aug 19, 2016 at 22:25
  • Thank you, that explains the discrepancy. I'm not really trying to return anything though, just push to a new list. I'm new to JavaScript and I'm a little confused. Commented Aug 19, 2016 at 22:26
  • Did that fix your problem? I wasn't sure if it would, I just wanted to explain that bit of functionality because in your question you seemed unsure of how it worked. Commented Aug 19, 2016 at 22:27
  • After thinking over it for a second I still don't know where to go. My goal isn't to return a value, but rather push a value to an array while inside the function. I edited my comment as you posted, sorry. Commented Aug 19, 2016 at 22:33

2 Answers 2

1

Array.prototype.find expects a callback function as first parameter, which is not what you supply and probably not thought of.

Sign up to request clarification or add additional context in comments.

1 Comment

Ya this was apparently the issue. I appreciate the help!
0

It's barking at if(!allProperties.find(p)). It's not liking the .find() because you have supplied it with an object as a parameter, not a function. .find() Docs Here

If you change it to if (allProperties.indexOf(p) === -1) {...} it works as expected.

var allProperties = [];
var sites = [
{
    "properties": [
        { "id": "111-11", "display": "Zone", "value": 1 },
    ]
}];

sites.forEach(site => site.properties.forEach(p => {
	if (allProperties.indexOf(p) === -1) {
		allProperties.push(p);
	}
}));

console.log(allProperties);

4 Comments

Ohhh I think find wants a function, not an object to match with.
Thanks for the help!
I think the function you want is allProperties.contains(p). But this is recent, so older browsers won't support it.
@Barmar Can you post documentation for .contains()? I see array.prototype.includes(), but I can't seem to find .contains() anywhere

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.