Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need a good way to locate elements in an array, or at least that element's index #102

Closed
shrickus opened this issue Dec 1, 2017 · 2 comments · Fixed by #362
Closed

Need a good way to locate elements in an array, or at least that element's index #102

shrickus opened this issue Dec 1, 2017 · 2 comments · Fixed by #362

Comments

@shrickus
Copy link

shrickus commented Dec 1, 2017

I'm trying to do something that I thought would be easy, but running into some roadblocks...

As an example, let's try to convert an input Month abbreviation into the Date month number (0-based). It's easy to find out if the incoming string is in the array of months, using payload in $months, but finding out what position it occupies in the array is not so easy:

(
    $months := [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    ];
    $months~>$map(function($val, $idx) {
        $val = payload ? $idx : undefined
    })
)

A bit clunky, perhaps, but it returns the index number for every array element that is equal to the incoming string. I tried using the $reduce($array, function($total, $value)) -- but unlike the Javascript function of the same name, there is no index value passed as the 3rd argument. At a minimum, I think the $reduce() function should be extended to also pass $index as an optional argument.

But perhaps a pair of new functions would be more intuitive and simpler to use, such as:

  • $find(array, input) and the overloaded $find(array, function($value))
  • $indexOf(array, input) and the overloaded $indexOf(array, function($value))

Both functions take an array of "things", and either a similar "thing" to find, or a function that determines which element is a match (returns true or false).

@michaelthoward
Copy link

At a minimum, I think the $reduce() function should be extended to also pass $index as an optional argument.

+1

In addition to the optional 3rd argument of array index, the signature for the callback function should include an optional 4th argument which is the array being iterated over. This would be consistent with the ECMAScript behavior of reduce. Passing the array index and the parent array would also be more consistent with the signature of the callback argument to $map.

@andrew-coleman
Copy link
Member

PR #362 addresses the arity-4 reduce function part of this. The indexOf function remains open and tracked by #187

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants