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

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

Find Index Of the Same Element in Array

问题

  1. const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
  2. console.log(fruits.indexOf("Apple"));

有没有办法找到数组中相同元素的索引,例如,"Apple" 在索引 2 和 4,输出应该是一个包含 [2, 4] 的数组?任何帮助将不胜感激 在数组中查找相同元素的索引。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. const fruits = [&quot;Banana&quot;, &quot;Orange&quot;, &quot;Apple&quot;, &quot;Mango&quot;,&quot;Apple&quot;];
  2. 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

  1. const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
  2. const indexes = fruits.reduce((r, n, i) => {
  3. n === "Apple" && r.push(i);
  4. return r;
  5. }, []);
  6. console.log(indexes);

也可以使用 filter 方法来实现:

  1. const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
  2. var keys = [];
  3. var filtered = fruits.filter((e, i) => {
  4. if (e === "Apple") {
  5. keys.push(i);
  6. }
  7. });
  8. 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 -->

  1. const fruits = [&quot;Banana&quot;, &quot;Orange&quot;, &quot;Apple&quot;, &quot;Mango&quot;,&quot;Apple&quot;];
  2. const indexes = fruits.reduce((r, n, i) =&gt; {
  3. n === &quot;Apple&quot; &amp;&amp; r.push(i);
  4. return r;
  5. }, []);
  6. console.log(indexes);

<!-- end snippet -->

It can be done also using filter as follows :

  1. const fruits = [&quot;Banana&quot;, &quot;Orange&quot;, &quot;Apple&quot;, &quot;Mango&quot;,&quot;Apple&quot;];
  2. var keys = [];
  3. var filtered = fruits.filter((e, i) =&gt; {
  4. if (e === &quot;Apple&quot;) {
  5. keys.push(i);
  6. }
  7. });
  8. 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:

确定