3

I'm trying to write a reduce statement that given an array of strings, return the array index that contains the word 'lace'.

I got it to work with a multi-line if statement, but it doesn't work when I use a single-line if statement:

input array

arr = [ 'tasselled', 'black', 'low-top', 'lace-up' ]

expected output

[3] // since the string 'lace' is in the 3rd index of the array

My code

// works (multi-line if statement)
arr.reduce( function(a,e,i) {
    if (e.indexOf('lace') >= 0) {
      a.push(i)
    }
    return a
  }, [])

// returns [3]
// doesn't work (single-line if statement)
arr.reduce( (a,e,i) => e.indexOf('lace')>=0 ? a.push(i) : 0, []);

// side note - can you do single-line if-statements without the else statement? (without the ': 0')

// returns error:
TypeError: a.push is not a function
Ben Watson
  • 5,357
  • 4
  • 42
  • 65
tbd_
  • 1,058
  • 1
  • 16
  • 39

2 Answers2

3

The main reason it's not working is because your ternary operation returns a number in both scenarios. .push() returns the length of the array and not the array itself.

So you can change it to use concat:

const arr = [ 'tasselled', 'black', 'low-top', 'lace-up' ]
const output = arr.reduce((a,e,i) => e.includes('lace') ? a.concat(i) : a, []);

console.log(output)

Another option is to filter the keys of the array

const arr = [ 'tasselled', 'black', 'low-top', 'lace-up' ]
const output = [...arr.keys()].filter(i => arr[i].includes('lace'))

console.log(output)
adiga
  • 34,372
  • 9
  • 61
  • 83
2

In your reduce statement if indexOf <0 then you return 0 instead of array, try

arr = [ 'tasselled', 'black', 'low-top', 'lace-up' ];

let r=arr.reduce( (a,e,i) => (e.indexOf('lace')>=0 ? a.push(i) : 0, a), []);

console.log(r);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    Got it. The placement of parentheses was important here. Not sure how obvious that would be to newcomers. – RichS May 07 '19 at 03:41
  • 1
    @RichS the parentheses is not important for implicit returns but here it is used for the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator) – adiga May 07 '19 at 03:54
  • Good clarification. – RichS May 07 '19 at 04:06