简体   繁体   English

检查数组的某些元素是否相等

[英]Check if some elements of array are equal

I found only a question "If all the elements are equal". 我只发现了一个问题“如果所有元素都相等”。 It doesn't suit me, I need another thing: Scan the array and take elements that are equal and push them to another array. 它不适合我,我还需要另一件事:扫描数组并获取相等的元素,然后将其推入另一个数组。

Sample Input: 输入样例:

arr = [1, 3, 3, 1]

Sample Output: 样本输出:

group = [[1,1],[3,3]]

Here's my code: 这是我的代码:

arr = [1, 3, 3, 1];
group = [];

pickNums = (a,b) => {
... ? group.push([a]) : null

arr.reduce(pickNums);

And I don't know what to write instead of "...". 而且我不知道写什么而不是“ ...”。 Do you have any ideas? 你有什么想法?

You could take a Map and group all values in the same group. 您可以制作一个Map并将所有值分组在同一组中。

 var array = [1, 3, 3, 1], groups = Array.from( array .reduce((m, v) => m.set(v, [...(m.get(v) || []), v]), new Map) .values() ); console.log(groups); 

Collect the items to a dictionary using Array.reduce() , then use Object.values() to convert back to array: 使用Array.reduce()将项目收集到字典中,然后使用Object.values()转换回数组:

 const arr = [1, 3, 3, 1]; pickNums = (arr) => Object.values(arr.reduce((r, n) => { r[n] = r[n] || []; r[n].push(n); return r; }, {})); const groups = pickNums(arr); console.log(groups); 

Sounds like this could be solved optimally by keeping a counter of similar elements using an Object/Hash. 这样的声音可以通过使用Object / Hash保留相似元素的计数器来最佳解决。

const array = [1, 3, 3, 1];
const elementCounterObject = {};
array.map(element => {
   if (!elementCounterObject[element]) {
       elementCounterObject[element] = 1;
   } else {
       elementCounterObject[element] += 1;
   }
});

console.log(elementCounterObject);   // result: {1: 2, 3: 2}

// converting elementCounterObject to display output as per requirement
const resultingArrayToDisplay = [];

for (let element in elementCounterObject) {
    const numberOfInstances = elementCounterObject[element];
    const elementToNumberOfInstanceArray = new Array(numberOfInstances).fill(parseInt(element));
    resultingArrayToDisplay.push(elementToNumberOfInstanceArray);
};

console.log(resultingArrayToDisplay); // result: [[1,1], [3,3]]

I've made this snippet verbose so that you could understand the algorithm behind this. 我将此代码段设为冗长的,以便您可以了解其背后的算法。 Some fluff could obviously be shaved off to make it concise but I hope this resolves your query 显然可以将一些绒毛刮掉以使其简洁,但我希望这可以解决您的查询

this is what you want : 这就是你想要的:

    const arr = [1, 3, 3, 1];
    let groups = [];
    arr.map((item)=>{
          const ar2 = arr.filter( sec => sec == item );
          if (! groups.filter( sec => sec.indexOf(item)>-1).length) {
            groups.push(ar2);
          }
     });

    console.log(groups);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM