JQuery 中有没有一种方法可以遍历字符串数组并返回新数组来排序该数组中的匹配字符串?

我只是在学习 jQuery,这是我的第一个项目之一,如果这是一个简单的问题,我深表歉意。


所以假设我有一个这样的数组:


const array = ["electric", "fire", "flying", "electric", "water", "electric", "water", "electric", "fire", "flying", "electric", "water"];

在这种情况下,我希望能够返回 4 个新数组,如下所示:


[“electric”, “electric”, “electric”, “electric”, “electric”]

[“fire”, “fire”]

[“flying”, “flying”]

[“water”, “water”, “water”] 

我已经尝试阅读不同的数组方法和一些以前在这里提出的问题,但我没有看到任何与此相关的内容。


临摹微笑
浏览 108回答 4
4回答

郎朗坤

您可以使用简单map的方法对项目进行分组:const array = ["electric", "fire", "flying", "electric", "water", "electric", "water", "electric", "fire", "flying", "electric", "water"];let map = {};for(let i = 0; i < array.length; i++){&nbsp; &nbsp; &nbsp;let item = array[i];&nbsp; &nbsp; &nbsp;if(!map[item])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map[item] = [ item ];&nbsp; &nbsp; &nbsp;else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map[item].push(item);}console.log(Object.values(map));

莫回无

您可以使用Array#reduce一个对象来存储数组中的每个元素,从而创建一个数组数组。const array = ["electric", "fire", "flying", "electric", "water", "electric", "water", "electric", "fire", "flying", "electric", "water"];const res = Object.values(&nbsp; &nbsp; &nbsp;array.reduce(&nbsp; &nbsp; &nbsp; (acc,curr)=>((acc[curr]=acc[curr]||[]).push(curr), acc), {}&nbsp; &nbsp; &nbsp;));console.log(res);

繁星点点滴滴

欢迎来到堆栈溢出。希望你喜欢这里。随意参加导览并查看如何提供最小的、可重现的示例您可以使用数组.map()和.filter()方法——您真的不需要为此使用 jQuery——如下所示:let&nbsp;chunks&nbsp;=&nbsp;array.map(a&nbsp;=>&nbsp;array.filter(x&nbsp;=>&nbsp;x&nbsp;===&nbsp;a)) &nbsp;&nbsp;&nbsp;&nbsp;.filter((item,&nbsp;index)&nbsp;=>&nbsp;array.indexOf(item[0])&nbsp;===&nbsp;index);const array = ["electric", "fire", "flying", "electric", "water", "electric", "water", "electric", "fire", "flying", "electric", "water"];let chunks = array.map(a => array.filter(x => x === a)).filter((item, i) => array.indexOf(item[0]) === i);console.log( chunks );

www说

这应该工作:const array = ["electric", "fire", "flying", "electric", "water", "electric", "water", "electric", "fire", "flying", "electric", "water"]console.log(array.reduce((acc, el) => {&nbsp; &nbsp; acc[el.charAt(0)] = acc[el.charAt(0)] ? [...acc[el.charAt(0)], el] : [el];&nbsp;&nbsp; &nbsp; return acc}, {}))您reduce是元素,然后基于以下内容构建生成的对象:如果已经有第一个字母的条目,则推送当前元素否则,将当前第一个字母和仅包含当前元素的数组关联到该条目注意:你实际上可以将它减少到一个关联数组,这取决于你哪个更符合你的要求
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript