The code that I needed is part of a larger project. In this project, I loop through a CSV file and output only the product names that have no variants. This is what the project looks like but I am getting the wrong output.
const parse = require('csv-parse');
const fs = require('fs');
const data = [];
var names = [];
var colorArray = [];
var namesArray = [];
var excludeNames = [];
function getDifferentNames(names) {
for(var i = 0; i < names.length; i++){
if(!namesArray.includes(names[i])){ // if not in array:
namesArray.push(names[i]); // add to array
} else { // already in array:
excludeNames.push(names[i]); // add to our exclude list
}
}
// now we must remove our exclude list from the names list:
var filtered = namesArray.filter(function(value, index, arr){
return !excludeNames.includes(value);
});
return filtered;
}
fs.createReadStream('spreadsheets/input.csv')
.pipe(parse({ delimiter: ',' }))
.on('data', (r) => {
data.push(r);
})
.on('end', () => {
for(var i = 0; i < data.length; i++){
product_name = getDifferentNames([data[i][0]]);
colorArray.push([product_name]);
flatArray = [...colorArray];
console.log(flatArray);
}}
)
If I am understanding correctly, you are trying to create an array that contains only the names that appear only once in your original array. Your getDifferentNames function should do that. Here is your function with simple input:
If no elements are being removed from your names then the items are not âequalâ in a JavaScript sense. Are they objects? You cannot compare objects for equality. If theyâre just strings, there must be some variation in the strings. Iâm assuming that you have narrowed down your problem to the getDifferentNames function.
However, instead of just building an array then creating a Set from it, just insert it into a Set to begin with.
As for ArielLeslie comment about comparing objects, thereâs exceptions to the rule. If thereâs no references as the key or value you can compare objects for equality.
Implies your getDifferentNames function is returning something. And if you look at that function, thereâs no returns. All functions return undefined if not explicit.
But thatâs a small issue.
If ultimately youâre just trying to get a list with no repeats you only need to do:
const uniqueProducts = data.reduce((a, b) => {
let [ products ] = b;
return new Set([...a, ...products]);
}, new Set());
Just to give you a pseudo code ,you can create an object from the array by iterating over it,where in the key will be your array element and value will be count of element.
After that use Object.keys and use filter method ,filtering out value === 1.