我看过其他与此类似的问题,但是没有找到与我要尝试的答案相符的答案。

我有一个多维数组:

var arr = [
["apple","ghana",15],
["apple","brazil",16],
["orange","nigeria",10],
["banana","ghana",6]
]

我想仅通过查看包含水果名称的第一列来过滤数组,并返回唯一值的数组。因此它将如下所示:
var uniqueArr = [
["apple","ghana",15],
["orange","nigeria",10],
["banana","ghana",6]
]

我想提供一个可以做到这一点的功能。我努力了:
    function isUnique (rows,index,self) {
      return self.indexOf(rows) === index
    }

但这没有用。任何帮助,将不胜感激!

最佳答案

使用reduce获取结果。

var arr = [["apple","ghana",15],["apple","brazil",16],["orange","nigeria",10],["banana","bangladesh",20],["banana","ghana",6]];

const res = arr.reduce((a, c) => {
	if (!a.find(v => v[0] === c[0])) {
		a.push(c);
	}
	return a;
}, []);

console.log(res);
.as-console-wrapper {
  min-height: 100% !important;
  top: 0;
}

07-24 17:44