skip to Main Content

How is it possible to map an array from a index and then map the rest based on a criteria.

const array = [4, 2, 8, 3, 4, 6];

const map = array.map((x, index) => {
  if(x<8){
    return index;
  };
 
});

console.log(">> "+map);

// Output array should be [1,3,4,5];  * Final array will be a lot bigger;

For example I want to search the array from index 1 and then return the indexes of all values less than 8.

Is map the best way or is there another?

Any help / advice would be appreciated.

2

Answers


  1. You can filter out the undefined values that are returned for the elements that don’t match the condition.

    const array = [4, 2, 8, 3, 4, 6];
    
    const result = array.map((x, index) => {
      if(x<8){
        return index;
      };
    }).filter(el => el !== undefined);
    
    console.log(">> "+result);

    Or do it in one loop using reduce.

    const array = [4, 2, 8, 3, 4, 6];
    
    const result = array.reduce((acc, x, index) => {
      if(x<8){
        acc.push(index);
      };
      return acc;
    }, []);
    
    console.log(">> "+result);
    Login or Signup to reply.
  2. If you want to use an Array method like .map() wherein the return value is transformed (ex. current number to current index) but return nothing when a criteria is not met (ie filtering), try .flatMap(). .flatMap() is .map() but it will flatten the returned array (see .flat()). The example below uses a ternary operator for the the criteria which means:

    /* If the current index (i) is greater than 
    OR equal to the given number (start = 1) ... */
     index >= start 
    // AND...
     &&
    // the current value (x) is less than 8...
     x < 8
    // return the current index (i).
     ? i
    /* Otherwise return an empty array 
    (which will be flattened to nothing).*/
     : []
    
    const array = [4, 2, 8, 3, 4, 6];
    const start = 1;
    
    const result = array.flatMap((x, i) => i >= start && x < 8 ? i : []);
    
    console.log(">> "+result);
    
    /** 
     * Output array should be [1,3,4,5];  
     * Final array will be NOT be bigger because the callback function returns 
     * just an index number OR nothing at all for a given number value
     */
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search