在数组中查找相同元素的索引。

huangapple go评论74阅读模式
英文:

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 = [&quot;Banana&quot;, &quot;Orange&quot;, &quot;Apple&quot;, &quot;Mango&quot;,&quot;Apple&quot;];
 console.log(fruits.indexOf(&quot;Apple&quot;) );

<!-- 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 = [&quot;Banana&quot;, &quot;Orange&quot;, &quot;Apple&quot;, &quot;Mango&quot;,&quot;Apple&quot;];

const indexes = fruits.reduce((r, n, i) =&gt; {
  n === &quot;Apple&quot; &amp;&amp; r.push(i);
  
  return r;
}, []);

console.log(indexes);

<!-- end snippet -->

It can be done also using filter as follows :

const fruits = [&quot;Banana&quot;, &quot;Orange&quot;, &quot;Apple&quot;, &quot;Mango&quot;,&quot;Apple&quot;];
var keys = [];
var filtered = fruits.filter((e, i) =&gt; {
  if (e === &quot;Apple&quot;) {
    keys.push(i);
  }
});
console.log(keys);

huangapple
  • 本文由 发表于 2023年2月26日 21:47:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定