Javascript get subset of array

Asked
Active3 hr before
Viewed126 times

5 Answers

subsetjavascriptarray
90%

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array, The original array will not be modified

Example_snippet/controller/utility/_subset.js/ slice() slice(start) slice(sta. . .
slice()
slice(start)
slice(start, end)
load more v
88%

Search Answer Titles

Example_snippet/controller/utility/_subset.js/ // array.slice(start, end) con. . .
// array.slice(start, end)
const FRUITS = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = FRUITS.slice(1, 3);
// citrus => [ 'Orange', 'Lemon' ]

// Negative values slice in the opposite direction
var fromTheEnd = FRUITS.slice(-3, -1);
// fromTheEnd => [ 'Lemon', 'Apple' ]
load more v
72%

Meta Stack Overflow , Stack Overflow Public questions & answers , Stack Overflow help chat ,Stack Overflow en español

Example_snippet/controller/utility/_subset.js/ const ar = [1, 2, 3, 4, 5]; . . .
const ar = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
load more v
65%

The slice() method returns selected elements in an array, as a new array,,slice() selects the elements starting at the given start argument, and ends at, but does not include, the given end argument

Example_snippet/controller/utility/_subset.js/ slice(). . .
slice()
load more v
75%

Write a JavaScript function to get all possible subset with a fixed length (for example 2) combinations in an array,,See the Pen JavaScript - Get all possible subset with a fixed length combinations in an array-function-ex- 21 by w3resource (@w3resource) on CodePen

Example_snippet/controller/utility/_subset.js/ <!DOCTYPE html> <html> <head> . . .
<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
   <title>JavaScript array subset</title>
</head>

<body>

</body>

</html>
Step 2 continued with function subset(arra, arra_siz. . .
function subset(arra, arra_size) {
   var result_set = [],
      result;

   for (var x = 0; x < Math.pow(2, arra.length); x++) {
      result = [];
      i = arra.length - 1;
      do {
         if ((x & (1 << i)) !== 0) {
            result.push(arra[i]);
         }
      } while (i--);

      if (result.length >= arra_size) {
         result_set.push(result);
      }
   }

   return result_set;
}

console.log(subset([1, 2, 3], 2));
Step 3 continued with [[2,1],[3,1],[3,2],[3,2,1]] . . .
[
   [2, 1],
   [3, 1],
   [3, 2],
   [3, 2, 1]
]
load more v