Could not get this point of javascript function - javascript

This is the code below, I am confused about this line.
What is this code doing? where does this title ( === title) comes from.
Plz, can anybody explain me about this?
var duplicateNote = notes.filter((note) => note.title === title);
var addNote = (title, body) => {
var notes = [];
var note = {
title,
body
}
try {
var notesstring = fs.readFileSync('notes-data.json');
notes = JSON.parse(notesstring);
} catch (e) {
}
console.log(Array.isArray(notes));
var duplicateNote = notes.filter((note) => note.title === title);

the filter function allow you to create a new array after filtering vaues of an old one
var duplicateNote = notes.filter((note) => note.title === title);
create an array duplicateNote containing entries of note where the entry's title is strictly equal to the title passed when calling the function.
It is equivalent to :
var duplicateNote = []
for (let note of notes) {
if (note.title === title) {
duplicateNote.push(note)
}
}

Related

How to generate HTML text with a for loop?

I have a list of expenses, I want to create a html code to iterate over all the expenses and show their name. I am not working with the DOM, I literally want to save the html code in a variable, so I can generate a pdf file with it.
This is what I tried:
lets say I have this array
const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]
const testHtml = () => {
for(let i of spents) {
const title = `<h1>${i.expenseName}</h1>`
}
}
testHtml()
This is the result I want, something like:
htmlResult = "<h1>${i.expenseName}</h1> <h1>${i.expenseName}</h1>"
by the way, This is for a react native app.
I think this will work for you.
const spents = [{expenseName: "Pizza"},{expenseName: "Home"}]
const testHtml = () => {
let title = '';
for(let i of spents) {
title += `<h1>${i.expenseName}</h1>`
}
return title;
}
testHtml()
You could use Array.prototype.reduce().
const spents = [{
expenseName: "Pizza"
}, {
expenseName: "Home"
}];
const result = spents.reduce((prev, curr, index) => index === 0 ? curr.expenseName : `<h1>${prev}</h1> <h1>${curr.expenseName}</h1>`, '');
document.body.append(result);

How to filter an array by two indvidual strings from an object?

I'm working on a project where I need to filter 13 items by two different select box values, and I'm getting stuck on persisting the filter.
I have two select boxes that I've selected like so:
let pickupLocation = document.querySelector("#pa_location"); //values are 'complete-set', 'neck', 'bridge'.
let pickupType = document.querySelector("#pa_type1"); // Values are 'soapbar', 'dogear', 'short'.
What's Working:
I'm initializing an object like so:
const activeFilters = {};
To populate the values like so:
//Persist the Complete Set / Single
pickupLocation.addEventListener("change", function () {
if (pickupLocation.value === "complete-set") {
activeFilters.location = "set";
} else {
activeFilters.location = "single";
}
});
pickupType.addEventListener("change", function () {
if (pickupType.value === "soapbar") {
activeFilters.type = "soapbar";
} else if (pickupType.value === "dogear") {
activeFilters.type = "dogear";
} else {
activeFilters.type = "short";
}
});
// Returns something like
// {location: single, type: dogear}
I'm trying to filter an array of input elements by their value. I have 13 inputs each with a value containing words like set, single, dogear, soapbar etc.
Where I'm stuck:
I have a filter function that I'm trying to filter the values of these inputs by two values of the activeFilters object:
const performFilter = (covers) => {
let results;
let filteredValues = Object.values(activeFilters);
filteredValues.forEach((value) => {
results = covers.filter((cover) => cover.value.indexOf(value) !== -1);
});
return results;
};
The problem is my function is returning only one of the two words. For instance, if the my activeFilters object is {location: set, type: dogear} the filtered results array contains only one of them. Where am I going wrong?
Edit:
This function returns all inputs that match one of the activeFilters, and I apologize if I wasn't clear above, but I'd like it to match ALL of the Active Filters. Is this possible with the function below?
const performFilter = (covers) => {
let results = []; // initialise the array
let filteredValues = Object.values(activeFilters);
filteredValues.forEach((value) => {
let res = covers.filter((cover) => cover.value.indexOf(value) !== -1);
results.push(...res);
});
console.log(results);
};
CODEPEN:
Codepen!
const performFilter = (covers) => {
let results = []; // initialise the array
let filteredValues = Object.values(activeFilters);
filteredValues.forEach((value) => {
let res = covers.filter((cover) => cover.value.indexOf(value) !== -1);
// push the value it find individually
// you were overriding the previous value with result = filter()
results.push(...res);
});
return results;
};
// according to Edited question
const performFilter = (covers) => {
let results = []; // initialise the array
let filteredValues = Object.values(activeFilters);
return covers.filter((cover) => filteredValues.every(value => cover.value.indexOf(value) !== -1));
};
I'm not sure if I understood clearly your question, so feel free to comment it.
First, I suggest you to filter your covers array and inside the filtering function iterate through your selected filters. This is because the filter function returns the array already filtered and so you don't need to assign it to a result variable or things like that. So based on that, try this:
const performFilter = (covers) => {
let results;
let filteredValues = Object.values(activeFilters);
const filteredCovers = covers.filter((cover) => {
return cover.value.split("-").some((tag) => filteredValues.includes(tag))
});
console.log(filteredCovers)
};

How to find object which id is not available in another array

I have 2 Array of objects. In which one is the original array, and another array contains the modified array. The modified array can contain new objects, edited object, or deleted object in settingValueDtoList
Currently, I am writing code for a new record in settingValueDtoList. If I am adding some new object in any settingValueDtoList then its id will be like a0, or a1 or a2 like this. I am just iterating both arrays and checking if id is not present in the original array, it means it is a new object, I want to push that object into my addSettingArray variable.
How can I fetch that new record whose id is not present in the original array?
This is what I tried.
compareSetting(settingArray: Array<any>) {
console.log('abc', this.settingObject)
console.log('settingArray',settingArray)
let settingIndex = 0;
this.settingObject.forEach(unmodifiedSetting => {
let modifiedSetting = settingArray[settingIndex];
modifiedSetting.settingValueDtoList.forEach(editedSettingValue => {
unmodifiedSetting.settingValueDtoList.forEach(uneditedSettingValue => {
if(editedSettingValue.id != uneditedSettingValue.id) {
this.addSettingArray.push(editedSettingValue);
}
});
})
settingIndex++;
})
console.log('add', this.addSettingArray)
}
Try like this:
compareSetting(settingArray: Array<any>) {
console.log('abc', this.settingObject)
console.log('settingArray',settingArray)
let settingIndex = 0;
this.settingObject.forEach(unmodifiedSetting => {
let modifiedSetting = settingArray[settingIndex];
modifiedSetting.settingValueDtoList.forEach(editedSettingValue => {
let isNewEntry = true;
unmodifiedSetting.settingValueDtoList.forEach(uneditedSettingValue => {
if(editedSettingValue.id == uneditedSettingValue.id) {
isNewEntry = false;
}
});
if (isNewEntry){
this.addSettingArray.push(editedSettingValue);
}
})
settingIndex++;
})
console.log('add', this.addSettingArray)
}
Edit:
More abstract for better understanding:
array1.forEach(entry1 =>
{
let isNewEntry = true; // says if entry1 is not present in array2
array2.forEach(entry2 =>
{
if(entry1.id == entry2.id)
{
isNewEntry = false; // the entry1 was found in array2
}
});
if (isNewEntry)
{
// the entry1 was not found in array2 - do whatever you want here
}
});

How to get value from one of several possible URL parameters?

I want to retrieve values form url parameters, but the parameters are not constant: it can be "referer=" or "utm_source=" or "source=".
I can get the value with
url.searchParams.get("referer");
Complete script for now :
function() {
var url_string = window.location.href;
var url = new URL(url_string);
var ref = url.searchParams.get("referer");
if (ref == undefined) {
return "No Referer";
} else {
return ref;
}
}
Can I include some regex like:
var ref = url.searchParams.get.match(/referer|source|utm\_source/g);
Can I include some regex
No. That isn't a feature of get.
You can use a set of ||s:
var ref = url.searchParams.get("referer") || url.searchParams.get("source") || url.searchParams.get("utm_source");
Or take an array of key names, map them to the values in the URL, filter out any which don't have a value, then take the first (and presumably only) value off the array.
var possible_key_names = ["referer", "source", "utm_source"];
var ref = possible_key_names
.map(name => url.searchParams.get(name))
.filter(value => !!value)
.shift();
You can loop over the searchParams like so:
var url = new URL("https://example.com/page?referer=&utm_source=google");
var value;
for (var [key, val] of url.searchParams) {
if (key.match(/^(referer|source|utm_source)$/) && val !== "") {
value = val;
break;
}
}
console.log(value);

Draft.js. How to get all entities data from the ContentState

From official docs I know about 2 methods: get entity by its key and get last created entity. In my case, I also need a method to access all entities from current ContentState.
Is there any method that could perform this? If not, is there a one that can provide all entities keys?
const getEntities = (editorState, entityType = null) => {
const content = editorState.getCurrentContent();
const entities = [];
content.getBlocksAsArray().forEach((block) => {
let selectedEntity = null;
block.findEntityRanges(
(character) => {
if (character.getEntity() !== null) {
const entity = content.getEntity(character.getEntity());
if (!entityType || (entityType && entity.getType() === entityType)) {
selectedEntity = {
entityKey: character.getEntity(),
blockKey: block.getKey(),
entity: content.getEntity(character.getEntity()),
};
return true;
}
}
return false;
},
(start, end) => {
entities.push({...selectedEntity, start, end});
});
});
return entities;
};
How I get the all entities keys:
const contentState = editorState.getCurrentContent()
const entityKeys = Object.keys(convertToRaw(contentState).entityMap)
result:
[0, 1]
then you can call the getEntity(key) method to get the responding entity.
this is how convertToRaw(contentState) looks:
Bao, You will find it inside key called 'blocks'.
convertToRaw(contentState).blocks.map(el=>el.text)
It will give you an array of raw text.
Unfortunatelly your suggested way using convertToRaw doesnt work because it reindexes all keys to ["0", .., "n"], but the real keys differ when you act with the editor. New ones > n will be added and unused will be omitted.
const rawState = convertToRaw(contentState)
const { entityMap } = rawState;
This entityMap will have list of all entities. But this is an expensive conversion. Because, it will convert whole thing to raw. A better way is loop through blocks and check for entity.
You'll have to look at every character:
const { editorState } = this.state; // assumes you store `editorState` on `state`
const contentState = editorState.getCurrentContent();
let entities = [];
contentState.getBlockMap().forEach(block => { // could also use .map() instead
block.findEntityRanges(character => {
const charEntity = character.getEntity();
if (charEntity) { // could be `null`
const contentEntity = contentState.getEntity(charEntity);
entities.push(contentEntity);
}
});
});
Then you could access it via:
entities.forEach((entity, i) => {
if (entity.get('type') === 'ANNOTATION') {
const data = entity.get('data');
// do something
}
})

Categories

Resources