javascript - 在数组中查找重复值和唯一值并将字符串转换为对象中的数组

标签 javascript arrays

我正在尝试查找数组中的所有唯一值,如果它有重复项,则应将重复 ID 的“名称”字段转换为数组。我试图显示唯一值,但我无法获取副本并隐藏到数组。

<!DOCTYPE html>
<html>
<body>

<p>Click the button to add a new element to the array.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>

//document.getElementById("demo").innerHTML = fruits;

function myFunction() {
var fruits = [{"name":"Banana","id":1}, 
{"name":"Grape","id":1}, 
{"name":"Apple","id":2},
{"name":"Mango","id":1},
{"name":"Banana","id":3}];

 let orgArray = [],output =[],l = fruits.length, i;
 for( i=0; i<l; i++) {
    if( orgArray[fruits[i].id]) continue;
    orgArray[fruits[i].id] = true;
    output.push(fruits[i]);
}
 console.log(output,'asdasdasdasdasd');





}
</script>

</body>
</html>

在上面的代码中,数组的最终值应该是这样的

  resultArray = [{"name":["Banana","Grape","Mango"],"id":1}, 
{"name":"Apple","id":2},
{"name":"Banana","id":3}];

最佳答案

这是一个分为两个阶段的过程。它通过分组水果的键创建一个映射,然后遍历该映射并返回一个对象数组;一个具有名称属性数组的对象,其中有多个元素,如果没有,则只有一个值。

var fruits = [{"name":"Banana","id":1}, {"name":"Grape","id":1}, {"name":"Apple","id":2},{"name":"Mango","id":1}, {"name":"Banana","id":3}];

// Iterate over the fruits array assigning
// an object as the initial value
const temp = fruits.reduce((acc, c) => {

  // Destructure the id and name from the
  // current element in the iteration
  const { id, name } = c;

  // If the object key doesn't already exist give a new array value
  // otherwise (if it exists - it's an array) concat the name to it
  acc[id] = (acc[id] || []).concat(name);

  // Return the object for the next iteration
  return acc;
}, {});

const out = Object.entries(temp).map(([key, values]) => {
  if (values.length > 1) return { name: values, id: key };

  // If there is only one element in the values array return
  // that element instead of the whole array
  return { name: values[0], id: key };
});

console.log(out);

延伸阅读

关于javascript - 在数组中查找重复值和唯一值并将字符串转换为对象中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58323574/

相关文章:

arrays - Ruby - 如何切片数组并根据条件对其元素求和

Javascript:为什么我的优化循环比更天真的循环慢

javascript - 使用 $scope - Angular Js

javascript - 在我的 React 应用程序中引入了分页。工作正常,但速度有些慢并且应用内导航 react 迟钝。未安装组件警告

javascript - 为什么我的 momentjs 对象上缺少 toJSON()?

c# - 无法将 FileInfo.Name 项从 string[] 添加到 List<string> 字段

javascript - CSS:适合内容的模态框

javascript - 使用 ReactJS 获取数据不显示在浏览器上

JavaScript 数组大括号与方括号

java - 阵列输出? java