Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #31567
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Re: Filter array of objects for property |
| Date | 2016-10-13 00:27 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <877f9d87y0.fsf@bsb.me.uk> (permalink) |
| References | <IKWdnYrudsxAIWPKnZ2dnUU7-XXNnZ2d@westnet.com.au> |
Andrew Poulos <ap_prog@hotmail.com> writes:
> If I have an array that looks like this
>
> var arr =
> [
> {
> a: "foo_2",
> b: "trigger_1",
> c: "bar_3"
> },
> {
> a: "foo_3",
> b: "foo_4",
> c: "bar_4"
> },
> {
> a: "foo_6",
> b: "trigger_5",
> c: "bar_5"
> }
> ...
> ];
>
> and to get an array of all "b" values that start with "trigger_" and
> end with a number I'm calling
>
> function getValues(theArr, pre) {
> var i = 0,
> fnd = [],
> tmp;
>
> for (i = 0; i < theArr.length; i++) {
> tmp = theArr[i].b;
> if ( /trigger_\d+$/.test(tmp) ) {
> fnd.push(tmp);
> }
> }
>
> return fnd;
> }
>
> While this works I'd like the argument "pre" to be a string I pass to
> the regexp so that I can test other values and not just "trigger_" but
> I don't know how.
You can construct a RegExp from a string:
RegExp(pre + '\\d+$').test(tmp)
> And secondly is there an easier way to get values for an array of
> objects?
One way would be to use map and filter. Combining these with the arrow
notation for functions you could write:
arr.map(x => x.b).filter(x => RegExp(pre + '\\d+$').test(x))
(ES6 would also permit you to write `${pre}\\d+$`)
--
Ben.
Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Filter array of objects for property Andrew Poulos <ap_prog@hotmail.com> - 2016-10-13 09:44 +1100
Re: Filter array of objects for property Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-10-13 00:27 +0100
Re: Filter array of objects for property Andrew Poulos <ap_prog@hotmail.com> - 2016-10-13 12:57 +1100
Re: Filter array of objects for property Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-10-13 11:21 +0100
Re: Filter array of objects for property Bunny Bocarisse <ben.usenet@bsb.me.uk> - 2016-10-13 13:28 +0100
csiph-web