Following is a code I implemented to create a bar chart using chart js in React app. Here it creates a bar chart with all the data in an array. But, I want to change this code only to give the output in the x-axis - destination, y-axis - no. of occurrence of this destination since it has many repeated destinations.
I searched methods to this but I couldn't get a correct solution.
Can anyone help me to do this?
const dataArrayY4 = [];
res.data.map(item => {
dataArrayY4.push(item.time)
})
const dataArrayX4 = []
res.data.map(item => {
dataArrayX4.push(item.destination)
})
this.setState({
data4: dataArrayY4,
labels4: dataArrayX4,
});
This could be done as follows:
const res = {
data: [
{ time: 1, destination: 'A'},
{ time: 3, destination: 'A'},
{ time: 2, destination: 'B'}
]
};
let tmp4 = [];
res.data.map((o, i) => {
const existing = tmp4.find(e => e.destination == o.destination);
if (existing) {
existing.time += o.time;
} else {
tmp4.push({time: o.time, destination: o.destination});
}
})
this.setState({
data4: tmp.map(o => o.time);
labels4: tmp.map(o => o.destination);
});
Above code could further be optimized by using Array.reduce() instead of Array.map().
I would make the code more efficient. Instead of dataArrayY4 being an array, I would make it an object that has a key of value and the number of occurrence of each value. This way, you can count all the number of occurrences of the all items in res.data
const dataArrayY4 = {};
res.data.map(item => {
dataArrayY4[item.destination] = (dataArrayY4[item.destination] || 0) + 1
})
const dataArrayX4 = []
res.data.forEach(item => {
dataArrayX4.push(item.destination)
})
this.setState({
data4: dataArrayY4,
labels4: dataArrayX4,
});
Then if you want to look for the occurrence of a particular value you
use this eg. Sri Lanka
this.state.data4['Sri Lanka']
Related
I'm currently completing a project where I have to build a Spotify playlist creator. For part of this, I need to add or remove tracks from the playlist. I've coded a method that appears to work, but it is different from the official solution, so I just want to see whether there is a reason I shouldn't do it my way.
Specifically, they use .find and .filter methods where I have used .includes. Is there a downside to what I've done?
Their code
addTrack(track) {
let tracks = this.state.playlistTracks;
if (tracks.find(savedTrack => savedTrack.id === track.id)) {
return;
}
tracks.push(track);
this.setState({ playlistTracks: tracks});
}
removeTrack(track) {
let tracks = this.state.playlistTracks;
tracks = tracks.filter(currentTrack => currentTrack.id !== track.id);
this.setState({playlistTracks: tracks});
}
My code
addTrack(track) {
let tracks = this.state.playlistTracks;
if (!tracks.includes(track)) {
tracks.push(track);
}
this.setState({playlistTracks: tracks});
}
removeTrack(track) {
let tracks = this.state.playlistTracks;
if (tracks.includes(track)) {
let index = tracks.indexOf(track);
tracks.splice(index, 1);
}
this.setState({playlistTracks: tracks});
}
Yes, there is a significant difference, because includes() will only return true if you pass it the actual instance (by that I mean a reference that points to the same object) of track that you are looking for.
The provided solution compares tracks only based on the track ID, so that is something different.
See the following example:
const tracks = [
{id: 1, title: "mysong1"},
{id: 2, title: "mysong2"},
]
function isTrackPresentIncludes(track){
return tracks.includes(track);
}
function isTrackPresentFind(track){
return tracks.find(it => it.id === track.id) !== undefined;
}
// this will be true
console.log("with includes(tracks[0]):\n", isTrackPresentIncludes(tracks[0]))
// this will be false as it's a different object
console.log("with includes({id: 1, title: \"mysong1\"}):\n", isTrackPresentIncludes({id: 1, title: "mysong1"}))
// this will be true
console.log("with find(tracks[0]):\n", isTrackPresentFind(tracks[0]))
// this will also be true
console.log("with find({id: 1, title: \"mysong1\"}):\n", isTrackPresentFind({id: 1, title: "mysong1"}))
You have the same issue with indexOf() in your removeTrack().
There is another thing I don't particularly like about the solution. find() returns the track that was found but that return value is never actually used so to my mind you should use some() instead which just returns true or false.
I don't think this is a problem here but it could potentially lead to unexpected behavior if an array would hold falsy values.
Consider this:
const arrayWithFalsyValues = [
0, // zero is falsy!
1,
2,
3,
4,
5,
6,
7,
8
]
function isPresent(toBeFound){
if(arrayWithFalsyValues.find(number => number === toBeFound)){
console.log(`Value ${toBeFound} found in array`);
}
else{
console.log(`Value ${toBeFound} NOT found in array`);
}
}
console.log("Array:", arrayWithFalsyValues)
// this will work as expected
console.log("Contains 3?")
isPresent(3)
console.log("Contains 8?")
isPresent(8)
console.log("Contains 10?")
isPresent(10)
// now search for the falsy value -> incorrect result
console.log("Contains 0?")
isPresent(0)
Issue is with referencing, You have make another reference of playlistTracks
addTrack(track) {
let { playlistTracks } = this.state;
let tracks = [...playlistTracks];
if (!tracks.includes(track)) {
tracks.push(track);
}
this.setState({ playlistTracks: tracks });
}
removeTrack(track) {
let { playlistTracks } = this.state;
let tracks = [...playlistTracks];
if (tracks.includes(track)) {
let index = tracks.indexOf(track);
tracks.splice(index, 1);
}
this.setState({ playlistTracks: tracks });
}
MY SUGGESTION
addTrack(track) {
const { playlistTracks } = this.state;
const tracks = [...playlistTracks];
const index = tracks.indexOf(track);
if (index < 0) {
tracks.push(track);
}
this.setState({ playlistTracks: tracks });
}
removeTrack(track) {
const { playlistTracks } = this.state;
const tracks = [...playlistTracks];
const index = tracks.indexOf(track);
if (index > -1) {
tracks.splice(index, 1);
}
this.setState({ playlistTracks: tracks });
}
this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.
How to prevent the suggestedResult from collapsing after clicking result using SearchWidget?
CodePen, copied below
// An open data address search API for France
const url = "https://api-adresse.data.gouv.fr/";
const map = new Map({
basemap: "streets-vector"
});
const view = new MapView({
container: "viewDiv",
map: map,
center: [2.21, 46.22], // lon, lat
scale: 3000000
});
const customSearchSource = new SearchSource({
placeholder: "example: 8 Boulevard du Port",
// Provide a getSuggestions method
// to provide suggestions to the Search widget
getSuggestions: (params) => {
// You can request data from a
// third-party source to find some
// suggestions with provided suggestTerm
// the user types in the Search widget
return esriRequest(url + "search/", {
query: {
q: params.suggestTerm.replace(/ /g, "+"),
limit: 6,
lat: view.center.latitude,
lon: view.center.longitude
},
responseType: "json"
}).then((results) => {
// Return Suggestion results to display
// in the Search widget
return results.data.features.map((feature) => {
return {
key: "name",
text: feature.properties.label,
sourceIndex: params.sourceIndex
};
});
});
},
// Provide a getResults method to find
// results from the suggestions
getResults: (params) => {
// If the Search widget passes the current location,
// you can use this in your own custom source
const operation = params.location ? "reverse/" : "search/";
let query = {};
// You can perform a different query if a location
// is provided
if (params.location) {
query.lat = params.location.latitude;
query.lon = params.location.longitude;
} else {
query.q = params.suggestResult.text.replace(/ /g, "+");
query.limit = 6;
}
return esriRequest(url + operation, {
query: query,
responseType: "json"
}).then((results) => {
// Parse the results of your custom search
const searchResults = results.data.features.map((feature) => {
// Create a Graphic the Search widget can display
const graphic = new Graphic({
geometry: new Point({
x: feature.geometry.coordinates[0],
y: feature.geometry.coordinates[1]
}),
attributes: feature.properties
});
// Optionally, you can provide an extent for
// a point result, so the view can zoom to it
const buffer = geometryEngine.geodesicBuffer(
graphic.geometry,
100,
"meters"
);
// Return a Search Result
const searchResult = {
extent: buffer.extent,
feature: graphic,
name: feature.properties.label
};
return searchResult;
});
// Return an array of Search Results
return searchResults;
});
}
});
// Create Search widget using custom SearchSource
const searchWidget = new Search({
view: view,
sources: [customSearchSource],
includeDefaultSources: false
});
// Add the search widget to the top left corner of the view
view.ui.add(searchWidget, {
position: "top-right"
});
3d version of code sample above
There is no documented way to do this through the API, as far as I can tell. But by adding the esri-search--show-suggestions to the SearchWidget, the suggestions will reappear:
const searchWidget = new Search({
view: view,
sources: [customSearchSource],
includeDefaultSources: false,
//autoSelect: false,
goToOverride: function(view, { target, options }) {
view.goTo(target, options);
const widget = document.querySelector('.esri-search__container')
widget.className += ' esri-search--show-suggestions'
},
});
Working CodePen here
I need the count of Status column in Sharepoint list. I have used React as the mode in spfx.
#autobind
private async _loadAsyncData(): Promise<Chart.ChartData> {
const items: any[] = await sp.web.lists.getByTitle("Sales").items.select("Title", "Salesamt", "Status").get();
let lblarr: string[] = [];
let dataarr: number[] = [];
items.forEach(element => {
lblarr.push(element.Title);
dataarr.push(element.Salesamt);
});
let chartdata: Chart.ChartData = {
labels: lblarr,
datasets: [{
label: 'My data',
data: dataarr
}]
};
return chartdata;
}
Can someone help me to get the count of items in the status column in the above code
Hi Nilanjan Mukherjee,
If your list is not very large, you can consider enumerating the whole list.
Another way is to use RenderListData() + CAML/Aggregations
Create a test list
Use below PnP code to get the count (note that the count is 2 while the row number is 3)
const caml: ICamlQuery = {
ViewXml: `<View><ViewFields><FieldRef Name="Title"/><FieldRef Name="johnjohn"/></ViewFields><Aggregations Value="On"><FieldRef Name="johnjohn" Type="Count"/></Aggregations></View>`
};
const r = await sp.web.lists.getByTitle('mm').renderListData(caml.ViewXml);
console.log(r);
Result:
Check below blog to get more details:
https://codeatwork.wordpress.com/2017/10/13/aggregation-using-caml-query/
BR
When i remove images from news i catch id, and id come to along.
How to write in array all this lonlies id ?
How to create streamIds array with streamId ?
this.state = {
mainImage: null,
mainImageUrl: "",
crop: {
aspect: 2 / 1
},
pixelCrop: null,
cropped: false,
loaded: false,
streamIds: []
};
removeImage(imageKey, streamId) {
const {singleNews} = this.props;
let streamIds = this.state.streamIds;
console.log(streamId);
singleNews.secondaryImages.splice(imageKey, 1);
if (!singleNews.secondaryImages.length) {
singleNews.secondaryImages = null;
delete singleNews.secondaryImages;
this.props.updateSingleNews(null, singleNews);
} else {
streamIds.push(streamId);
singleNews.secondaryImages.map(image => {
const index = singleNews.secondaryImages.indexOf(image);
if (index > -1) {
singleNews.secondaryImages.slice(index, 1);
FilesApi.getDocument(image.streamId).then(resp => {
singleNews.secondaryImages[index] = new File([resp], image.name, {lastModified: Date.now()});
});
}
});
this.props.updateSingleNews('streamIds', streamIds);
}
}
this is your method
If not in this func where i need to place
if you want to keep the array of ids in the same component, use
let streamIds = [];
at the top of your react component and do
removeImage (imageKey, streamId) {
console.log(streamId);
streamIds.push(streamId); // insert the item to array
}
in your removeImage method
if you want to keep the removed ids in the application state, then the concept is the same, but it need to be done on the state management tool you are using (like redux, mobx etc)