1

I am trying to filter an array with all the possible matches. How can i implement please guide me.

arr = [{test: 100}, {test: 100A}, {test: 100B}, {test: 100C}, {test: 101}, {test: 101}]
// i want to filter the above array which matches 100.

I have tried.
var arr1 = arr.filter(x => x.test === 100);
console.log(arr1);
it returns only {test: 100} instead i want {test: 100}, {test: 100A}, {test: 100B}, {test: 100C}
2
  • {test: 100A} is not valid javascript syntax, are you sure this is the array? Commented Aug 7, 2020 at 7:54
  • You'll get SyntaxError with your current arr. Commented Aug 7, 2020 at 7:56

4 Answers 4

2

Assuming your test values are actually strings, you can use String.startsWith to do the filtering:

arr = [
  {test: '100'}, {test: '100A'}, {test: '100B'},
  {test: '100C'}, {test: '101'}, {test: '101'}
];

arr1 = arr.filter(o => o.test.startsWith('100'));
console.log(arr1);

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

Comments

1

There are multiple ways you can do this:

You can use filter and includes function together to see if value test is 100 and other matching strings.

Using includes

let arr = [{test: '100'}, {test: '100A'}, {test: '100B'}, {test: '100C'}, {test: '101'}, {test: '101'}]

var arr1 = arr.filter(str => str.test.includes('100'));

console.log(arr1);

You can use filter will indexOf

Using indexOf

let arr = [{test: '100'}, {test: '100A'}, {test: '100B'}, {test: '100C'}, {test: '101'}, {test: '101'}]

var arr1 = arr.filter(str => str.test.indexOf('100') > -1);

console.log(arr1);

Comments

0

try this:

var arr1 = arr.filter(x => x.test.includes(100));

Comments

0

Since you are using ===, you are checking exact value and type.

If you want to filter based on value, first convert the string to value using parseInt and then compare.

const arr = [{test: '100'}, {test: '100A'}, {test: '100B'}, {test: '100C'}, {test: '101'}, {test: '101'}]

const res = arr.filter(({test}) => parseInt(test) === 100);

console.log(res);

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.