简体   繁体   中英

Calling Array.includes() on a accumulator raises a TypeError; .reduce()

I'm trying to reduce an Array that contains any duplicate words. Upon trying to return the result I get the follow error TypeError: acc.includes is not a function . The way I'm interpreting the error is that the method is not available for the array acc due to the version of JavaScript being used.

Am I correct in assuming this or is there something else going on here?

function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return acc.push(value);
    } else {
        return !acc.includes(value) ? acc.push(value) : "";
    }
  }, [])
}

You are not returning array in your function. Whatever you return from the callback of reduce() it will become acc for next iteration. You need to return the array.

push() method is inplace(it will modify original array) method which returns the length of new array not the new array with new value.

 function removeDuplicateWords (s) { return s.split(" ").reduce(function(acc, value, index, array) { if (array.indexOf(value) === array.lastIndexOf(value)) { return [...acc, value] } else { return !acc.includes(value) ? [...acc, value] : acc; } }, []) } console.log(removeDuplicateWords("hello hello hey"))

The same thing could be achieved using Set() and spread operator.

 const removeDups = str => [... new Set(str.split(' '))]; console.log(removeDups('hello hey hello'))

You can use filter instead like shown below. filter has three parameters item , index & array . And indexOf will return index of first occurrence of value. So it will always return first value only thus duplicate value will be removed.

 function removeDuplicateWords(s) { return s.split(" ").filter((x, i, a) => a.indexOf(x) === i); } console.log(removeDuplicateWords("hello hello hey"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM