Reputation: 105
I'm trying to compare for some duplicate value inside a loop because I need to do some logic. My problem is that I can't get the output that I expected.
var tempVal;
for (i = 0; i < obj.length; i++) {
var items = obj[i];
tempVal = items.fund;
console.log(tempVal);
console.log(tempVal == tempVal);
if(tempVal == tempVal){
//do something
}
In my example I have 2 same value in tempVal
variable. My console.log(tempVal == tempVal)
returns true
in first loop but I thought it would return null
or undefined
in first loop because there's nothing to compare because it's empty on the first loop. What I need is top first return false
then true
. Thanks
Upvotes: 0
Views: 110
Reputation: 2560
Looking at your code, I thought this is what you're trying to achieve:
var src = [
{
"index": 0,
"fund": 100
},
{
"index": 1,
"fund": 200
},
{
"index": 2,
"fund": 100
}];
var tempFunds = [];
const uniqueFunds = src.filter(item => {
if (tempFunds.indexOf(item.fund) === -1) {
tempFunds.push(item.fund);
return item;
}
});
// logs the array with unique funds
console.log(uniqueFunds);
You can implement an else
branch above if you want to deal with duplicate fund(s). Although there is no issue with your choice to use a for loop, you could also consider map
or filter
function(s) based on your problem.
Upvotes: 0
Reputation: 3240
You haven't defined the initial value. So obuse a variable compare with them self are always equal. Why are you not using another name for remove complexity also.
var tempVal;
for (i = 0; i < obj.length; i++) {
var items = obj[i];
temp = items.fund;
console.log(temp);
console.log(temp == tempVal);
if(temp == tempVal){
//do something
}
Upvotes: 0
Reputation: 222722
You are comparing the same variable, obviously they are equal, create another variable and compare.
tempVal = items.fund;
console.log(tempVal);
console.log(tempVal == tempVal); //both are same
Upvotes: 2