Javascript过滤器但返回键而不是值

此函数工作正常,但我不希望它返回值,但键:


const search = [2342,1900,1800,2310]


search = search.filter(function (el) { return el > 2200; });

所以它应该返回[0,3]而不是[2342,2310]


ibeautiful
浏览 184回答 3
3回答

撒科打诨

您可以获取密钥,然后使用它们访问数组,并基于此进行过滤:const search = [2342,1900,1800,2310];const result = Object.keys(search)  .filter(key => search[key] > 2200)  .map(key => Number(key))  console.dir(result)或者,对于更有趣的事情:const search = [2342,1900,1800,2310];const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);const filter = f => a => a.filter(f);const map = f => a => a.map(f);const toPairs = o => Object.keys(o)  .map(k => [k, o[k]]);  const take = i => a => a[i];const gte = a => b => b >= a;const toNumber = x => Number(x);const bigEnough = gte(2200);const itemOneIsBigEnough = pipe(  take(1),  bigEnough);const getTheFirstItemAsANumber = pipe(take(0), toNumber);const doTheThing = pipe(  toPairs,  filter(    itemOneIsBigEnough  ),  map(getTheFirstItemAsANumber),);const result = doTheThing(search);console.dir(result);

狐的传说

您可以获取键并按值检查过滤。const    search = [2342, 1900, 1800, 2310],    indices = [...search.keys()].filter(i => search[i] > 2200);console.log(indices);

阿晨1998

最简单的方法是只是Array#reduce项目:const search = [2342,1900,1800,2310]const result = search.reduce(function (result, el, index) {  if(el > 2200) {    result.push(index);  }  return result;}, []);console.log(result);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript