Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: Filter array of objects for property Date: Thu, 13 Oct 2016 00:27:03 +0100 Organization: A noiseless patient Spider Lines: 62 Message-ID: <877f9d87y0.fsf@bsb.me.uk> References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="d55b9a4918507de28ffdc8b5228c4096"; logging-data="2154"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18cUiuJqP6zKgLp4IprDzdHryVlIEpqAJg=" Cancel-Lock: sha1:D6ZB5PaKSSsPXpkroe9bkLbohXQ= sha1:fd+uU0gBCtpKpnY4+v2QMDxiepU= X-BSB-Auth: 1.184af6a00ee750472854.20161013002703BST.877f9d87y0.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:31567 Andrew Poulos 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.