英文:
Find Index Of the Same Element in Array
问题
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
console.log(fruits.indexOf("Apple"));
有没有办法找到数组中相同元素的索引,例如,"Apple" 在索引 2 和 4,输出应该是一个包含 [2, 4] 的数组?任何帮助将不胜感激
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
console.log(fruits.indexOf("Apple") );
<!-- end snippet -->
Is there a way to find the index of the same element in an array, for example, "Apple" is at the index of 2 and 4 and the output should be in an array [2,4] ? Any help will be very appreciated
答案1
得分: 2
你可以将数组减小到索引数组,其中值为 Apple:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
const indexes = fruits.reduce((r, n, i) => {
n === "Apple" && r.push(i);
return r;
}, []);
console.log(indexes);
也可以使用 filter
方法来实现:
const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
var keys = [];
var filtered = fruits.filter((e, i) => {
if (e === "Apple") {
keys.push(i);
}
});
console.log(keys);
英文:
You can reduce
the array to array of indexes, which value is Apple:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
const indexes = fruits.reduce((r, n, i) => {
n === "Apple" && r.push(i);
return r;
}, []);
console.log(indexes);
<!-- end snippet -->
It can be done also using filter
as follows :
const fruits = ["Banana", "Orange", "Apple", "Mango","Apple"];
var keys = [];
var filtered = fruits.filter((e, i) => {
if (e === "Apple") {
keys.push(i);
}
});
console.log(keys);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论