我正在尝试查找数组中的所有唯一值,如果它有重复项,则应将重复 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/