javascript 如何匹配数组中的相同值

0sgqnhkj  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(153)

例如,如果这是我的数组:

[
  {a: "b"},
  {a: "b"},
  {a: "c"},
  {a: "c"},
]

我如何修改数组,以便如果有更多的a具有相同的值,则将它们放在相同的索引中:

[
  {
    a: "b",
    a1: "b"
  },
  {
    a: "c",
    a1: "c"
  },
]
u5i3ibmn

u5i3ibmn1#

希望这会有所帮助:

var arr = [
  {a: "b"},
  {a: "b"},
  {a: "c"},
  {a: "c"}
];

var arr2 = [];
var arr3 = [];

Object.keys(arr).forEach(key => {
    Object.keys(arr[key]).forEach(keyx => {
        if (!(arr[key][keyx] in arr2)) {
            arr2[arr[key][keyx]] = [];
        }
        var k = keyx;
        var x = 1;
        var i = true;
        while (i === true) {
            if (!(k in arr2[arr[key][keyx]])) {
                i = false;
                arr2[arr[key][keyx]][k] = arr[key][keyx];
            }
            k = keyx + x;
            x++;
        }
    })
});

for (i in arr2) {
    arr3.push(arr2[i]);
}

//arr3 is the expected array

相关问题