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
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:
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.
Or shorter with Array.filter in ES6 as Arrow Function
returns
["A", "B", "C"]
You can archive this using Array
filter
method in javscript.Or else you can do it via another simplified way as below :
Even more Simplified :