在动态数组的对象元素Javascript中查找通用元素 [英] Find common elements within dynamic array's object elements Javascript

查看:45
本文介绍了在动态数组的对象元素Javascript中查找通用元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关此主题的问题很多,但我找不到直接解决我所遇到问题的答案.

There were a lot of questions asked about this topic, but I couldn't find the answer that addressed directly the issue I am having.

这里是一个:使用JavaScript在1个数组中查找公共元素

第一个区别是我有不同类型的数组,其元素是具有键-值对的对象,其中key是字符串,值是整数数组.

The first difference is that I have a different type of array, its elements are objects with key-value pair, where key is the string and the value is an array of integers.

第二个区别是数组是动态的,这意味着有时它可能有零个元素,而有时它可能有3个对象元素.

The second difference is that array is dynamic meaning that sometimes it may have zero elements and the other times it may have 3 object elements.

我在下面共享示例数组:

I am sharing the sample array below:

const array = [
  {"key1":[1,2,3]},
  {"key2":[2,3,4]},
  {"key3":[2,5,6]},
];

第三个区别是元素事项 order ,以便最终结果应输出所有后续数组中存在的第一个元素的值.

The third difference is that the order of elements matters so that final result should output the values of the first element that exist in all subsequent arrays.

结果应为:

const result = [2];

由于 2 是这三个元素的唯一共同整数.

Since 2 is the only common integer of these three elements.

如前所述,有时数组中可能只有1个或2个元素,或者根本没有元素,应该考虑这些情况.

As mentioned array sometimes might have just 1 or 2 or no elements in it and those cases should be accounted.

编辑1 :按照注释中的要求 array的值是唯一的

Edit 1: as asked in the comments the values of array are unique

推荐答案

由于一个值​​只能在数组中出现一次,因此可以合并数组,计算出现次数,并过滤不等于长度的出现原始数组.

Since a value can appear in array only once, you can concat the arrays, count the number of appearances, and filter our those that are not equal to the length of the original array.

const findRecuring = (array) =>
  [...
    [].concat(...array.map((o) => Object.values(o)[0])) // combine to one array
   .reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map()) // count the appearance of all values in a map
 ] // convert the map to array of key/value pairs
 .filter(([, v]) => v === array.length) // filter those that don't appear enough times
 .map(([k]) => k); // extract just the keys

/** Test cases **/
console.log('Several:', findRecuring([
  {"key1":[6,1,2,3,8]},
  {"key2":[2,6,3,4,8]},
  {"key3":[2,5,6,8]},
]).join());

console.log('None: ', findRecuring([
  {"key1":[9,0,11]},
  {"key2":[2,6,3,4,8]},
  {"key3":[2,5,6,8]},
]).join());

这篇关于在动态数组的对象元素Javascript中查找通用元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆