0

I have following array, When I type number '98' I want to show both results and when I typed '983' I want to show result of 'string 2' but when I type number '98' I did not get any result can anyone help me what I am doing wrong here??

here is my following code

    var array = [
        { name:"string 1", number:9845687, other: "that" },
        { name:"string 2", number:98325678, other: "that" }
    ];
    
    var foundValue = array.filter(obj=>obj.number===98);
    
    console.log(foundValue);

2 Answers 2

1

U can do this the following way using includes method

var array = [
    { name:"string 1", number:98456874, other: "that" },
    { name:"string 2", number:98325678, other: "that" }
];

var foundValue = array.filter(obj => {
  let n = obj.number.toString()
  if(n.includes('98')) return obj
});

console.log(foundValue);

Hope it helps

UPDATE

As u mention the number is not a string so what u can do is make it string before you comapre it will solve the issue

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

3 Comments

sorry my mistake number property is datatype number, and we cant applied include property on number type
u mean this ` number:98456874` ?
I would replace the entire filter callback with: obj => obj.number.toString().includes('98'). At least remove the if statement, because the filter only expects true or false, not an entire object.
0

You can use indexOf to check a string contains a substr.

    var array = [
        { name:"string 1", number:9845687, other: "that" },
        { name:"string 2", number:98325678, other: "that" }
    ];
    
    var foundValue = array.filter({
        var str = obj.number.toString();
        return str.indexOf(98) >= 0;
    });
    
    console.log(foundValue);

Comments

Your Answer

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