Search code examples
javascriptarraysangular7

How to fetch result of matching string from array?


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);


Solution

  • 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