skip to Main Content

Hi guys i am having a problem using javascript.
what i am doing is i have a list of string as follow

var data = ["A","B","c","Sam"];

I am trying to find A,B or C from my data array and if they exist I want them in another array and return the array.

I am trying the following code:

var data=["A","B","C","Sam"];

var result=[];
for(var i=0;i<source.length;i++){
    const res =source.includes('A') || source.includes('B') || source.includes('C');
    result.push(res);
    console.log(result);
}

Here the problem is it only returns true but not A B C. My further action would be — if the returned array has A B or C — to replace them with the suitable name.

3

Answers


  1. The problem with your code is that you’re checking if ‘A’, ‘B’, or ‘C’ exist in your data array (which is correct), but then you’re pushing the boolean result of that check (true or false) into your results array instead of the actual value. It’s like asking if there’s pizza in the fridge, and instead of taking the pizza, you’re taking a sticky note that says "yes , there’s pizza".

    You actually want to check each item in the array one by one and push the item itself into the new array if it matches ‘A’, ‘B’ , or ‘C’. Here’s how you could do it:

    var data = ["A", "B" , "C", "Sam"];
    
    var result = [];
    for(var i=0; i < data.length; i++) {
      if(data[i] === 'A' || data[i] === 'B' || data[i] === 'C') {
        result.push(data[i]);
      }
    }
    
    console.log(result);
    

    This code will loop through each item in your data array, and for each one, it’ll check if it’s ‘A’ , ‘B’, or ‘C’. If it is, it’ll push that item into the result array. So at the end, your result array will contain the items ‘A’, ‘B’, or ‘C’ from your data array if they exist.

    Login or Signup to reply.
  2. Or shorter with Array.filter in ES6 as Arrow Function

    let dataArr = ["A", "B" , "C", "Sam"];
    dataArr.filter(x => x === 'A' || x === 'B' || x === 'C')
    

    returns
    ["A", "B", "C"]

    Login or Signup to reply.
  3. You can archive this using Array filter method in javscript.

    const filter = ["A", "B", "C"];
    const data = ["A", "B", "C", "Sam"];
    
    const filteredArray = data.filter(item => filter.includes(item));
    
    console.log(filteredArray);

    Or else you can do it via another simplified way as below :

       const data = ["A", "B" , "C", "Sam"];
    console.log(data.filter(x => x === "A" || x === "B" || x === "C"))

    Even more Simplified :

        
    console.log(["A", "B" , "C", "Sam"].filter(x => x === "A" || x === "B" || x === "C"))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search