1

I have the following script, I need to return the following result:

{
      text: 'i love apples'
    }, {
      text: 'i eat my apple'
    }, {
      text: 'no apples on the table'
    }

with the following script I get an error.

What am I doing wrong, how to fix it (also another solution without using .match could be fine too)?

Notes: search value could be different, so script should be re-usuable.

let data = [{
  text: 'i love apples'
}, {
  text: 'i eat my apple'
}, {
  text: 'no apples on the table'
},{
  text: 'i love oranges'
}];
let search = 'apple'

let filter = data.filter(item=>{ return item.match(search)})
console.log(filter)

1
  • 2
    Are you looking for something more like item.text.match(search)? Commented Sep 19, 2017 at 19:08

3 Answers 3

3

use includes instead and make sure to reference the property in your iteration.

let data = [{
  text: 'i love apples'
}, {
  text: 'i eat my apple'
}, {
  text: 'no apples on the table'
}, {
  text: 'i love oranges'
}];
let search = 'apple';

let filter = data.filter(item => item.text.includes(search))
console.log(filter)

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, and you can also safely omit return and braces
@georg good point :), I just wanted to be consistent with his style. but ill change it.
1

You are just there, use item.text.match. where item is iterator to your data array.

let data = [{
  text: 'i love apples'
}, {
  text: 'i eat my apple'
}, {
  text: 'no apples on the table'
},{
  text: 'i love oranges'
}];
let search = 'apple'

let filter = data.filter(item=>{ return item.text.match(search)})
console.log(filter)

Comments

1

The only thing I feel you are missing is the item.text, match is a function on string instead of object, you want to go one level deeper to match the content.

let data = [{
  text: 'i love apples'
}, {
  text: 'i eat my apple'
}, {
  text: 'no apples on the table'
},{
  text: 'i love oranges'
}];
let search = 'apple'

let filter = data.filter((item)=>{ return item.text.match(search)})
console.log(filter)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.