JS Snippets: Array: Difference between revisions
From WikiMLT
mNo edit summary |
m Text replacement - "mlw-continue" to "code-continue" |
||
Line 2: | Line 2: | ||
== Intersect two Arrays == | == Intersect two Arrays == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const arr1 = [1, 2, 3, 4]; | const arr1 = [1, 2, 3, 4]; | ||
const arr2 = [1, 2, 5, 6]; | const arr2 = [1, 2, 5, 6]; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const intersection = arr1.filter(value => arr2.includes(value)); | const intersection = arr1.filter(value => arr2.includes(value)); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(intersection); | console.log(intersection); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 19: | Line 19: | ||
== Get an Array elements by an Array of indexes == | == Get an Array elements by an Array of indexes == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f']; | const arr1 = ['a', 'b', 'c', 'd', 'e', 'f']; | ||
const arr2 = [1, 3, 4, 0]; | const arr2 = [1, 3, 4, 0]; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const intersection = arr1.filter((value, index) => arr2.includes(index)); // arr2.includes(index) ? true : false | const intersection = arr1.filter((value, index) => arr2.includes(index)); // arr2.includes(index) ? true : false | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(intersection); | console.log(intersection); | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 07:29, 26 September 2022
Intersect two Arrays
const arr1 = [1, 2, 3, 4];
const arr2 = [1, 2, 5, 6];
const intersection = arr1.filter(value => arr2.includes(value));
console.log(intersection);
(2) [1, 2]
Reference: How to find the intersection of arrays in JavaScript by Reactgo
Get an Array elements by an Array of indexes
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f'];
const arr2 = [1, 3, 4, 0];
const intersection = arr1.filter((value, index) => arr2.includes(index)); // arr2.includes(index) ? true : false
console.log(intersection);
(3) ['a', 'b', 'd', 'e']