现有如下数据结构的代码,已进行了分类,如何找出不同类的第一个索引(B类索引为3,C类索引为5)?
const arr = [
{ type: "A", item: 11 },
{ type: "A", item: 22 },
{ type: "A", item: 33 },
{ type: "B", item: 44 },
{ type: "B", item: 55 },
{ type: "C", item: 66 },
{ type: "C", item: 77 },
{ type: "C", item: 88 },
{ type: "C", item: 99 },
{ type: "C", item: 1010 },
];
有方法如下,贴代码
const arr = [
{ type: "A", item: 11 },
{ type: "A", item: 22 },
{ type: "A", item: 33 },
{ type: "B", item: 44 },
{ type: "B", item: 55 },
{ type: "C", item: 66 },
{ type: "C", item: 77 },
{ type: "C", item: 88 },
{ type: "C", item: 99 },
{ type: "C", item: 1010 },
];
const typeArr = [];
arr.forEach((item) => {
typeArr.push(item.type);
});
console.log(typeArr); ['A', 'A', 'A', 'B','B', 'C', 'C', 'C','C', 'C']
const secondIndx = typeArr.indexOf("B");
const thirdIndx = typeArr.indexOf("C");
console.log(secondIndx);
console.log(thirdIndx);
// 代码些许不严谨,仅做参考