-2

I am trying to create an array of all string which has length more than zero.

let sampleArray2:string[] = ["hello","world","angular","typescript"];
let subArray:string[] = sampleArray2
    .map(() => sampleArray2
        .find(val => val.length > 5)
    );
console.log(subArray);

As expected, it is returning [ 'angular', 'angular', 'angular', 'angular' ] I wanted it to print [ 'angular', 'typescript' ]

I am specifically looking for a solution which uses both map and find together to accomplish this. How can I fix this?

Note: Though filter is a straightforward solution, I am trying to see if map and find can be used together to get the desired output.

codingsplash
  • 4,785
  • 12
  • 51
  • 90

4 Answers4

0

let subArray:string[] = sampleArray2.filter(i => i.length > 5);

see MDN web docs - Array.prototype.filter

Riscie
  • 3,775
  • 1
  • 24
  • 31
0

.find is not what you want - you want .filter.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

The problem is that your map() returns 'angular' 5 times.

A correct syntax using filter (and therefore preserving your types) should be :

let subArray:string[]= sampleArray2.filter(val=>val.length>5)
Mathieu K.
  • 903
  • 8
  • 27
0

You don't need the function map nor the function find.

Use the function filter.

let sampleArray2 = ["hello", "world", "angular", "typescript"];
let subArray = sampleArray2.filter(val => val.length > 5);

console.log(subArray);
Ele
  • 33,468
  • 7
  • 37
  • 75