How can i put loop and get values in javascript? - javascript

<script>
var data={
Data: {
name: 'aaaa',
number: '0003'
},
values: {
val: '-20.00',
rate: '22047'
},
user: [ '6|1|5', '10|1|15' ]
};
console.log(data);
console.log(data.user.length);
for(var i=0;i<data.user.length;i++) {
console.log(data.user[i]);
}
</script>
Above is my code i want to put loop and get values like this
this is my data user: [ '6|1|5', '10|1|15' ]
but i want to get like this:
userid - 6
roolno - 1
rank - 5
userid - 10
roolno - 1
rank - 15
how can i do this any one help me out ?

A simple map would do it (see plunker):
data.user.map(function(x) {
var parts = x.split('|');
return {
userid: parts[0],
roolno: parts[1],
rank: parts[2]
};
});
This would return you:
[
{
userid: 1,
roolno: 1,
rank: 5
},
{
userid: 10,
roolno: 1,
rank: 15
},
]

Related

Javascript re-order array of object by value

How do I re-order array of object showing below by follow value. If follow value is not -1, move the item below to the item that has the id value same as follow value.
Here is the example.
let charObj = [
{ id: 8, name: 'Catelyn Stark', follow: -1 },
{ id: 7, name: 'Jaime Lannister', follow: 8 },
{ id: 3, name: 'Jon Snow', follow: -1 },
{ id: 4, name: 'Daenerys Targaryen', follow: 7 },
{ id: 5, name: 'Sansa Stark', follow: 4 }
];
Expected output will be;
let charObj = [
{ id: 8, name: 'Catelyn Stark', follow: -1 },
{ id: 7, name: 'Jaime Lannister', follow: 8 },
{ id: 4, name: 'Daenerys Targaryen', follow: 7 },
{ id: 5, name: 'Sansa Stark', follow: 4 },
{ id: 3, name: 'Jon Snow', follow: -1 }
];
Not sure if I can use sort(). What is the best way to re-order this object?
I think this will do what you're asking. I'm sure it could be made more efficient, but unless your list gets quite large that shouldn't make much practical difference. Also, this assumes any character will only have one follower. If that's not the rule, then the function will have to be adjusted.
let charObj = [
{ id: 8, name: "Catelyn Stark", follow: -1 },
{ id: 7, name: "Jaime Lannister", follow: 8 },
{ id: 3, name: "Jon Snow", follow: -1 },
{ id: 4, name: "Daenerys Targaryen", follow: 7 },
{ id: 5, name: "Sansa Stark", follow: 4 }
];
function sortChars(chars) {
let result = [];
let leaders = chars.filter(c => c.follow === -1);
for (let i = 0; i < leaders.length; i++) {
let current = leaders[i];
while (current) {
result.push(current);
let next = charObj.find(c => c.follow === current.id);
current = next;
}
}
return result;
}
console.log(sortChars(charObj));

Max element in an array in dailogflow

I am trying to calculate max element in an array . I tried this code but it is returning [object Object]
Is there something i am missing while doing in dailogflow.
function studentgroup(agent){
let games = [
{ id: 1, name: 'Star Wars: Imperial Assault', votes: 3},
{ id: 2, name: 'Game of Thrones: Second Edition', votes: 4 },
{ id: 3, name: 'Merchans and Marauders', votes: 5 },
{ id: 4, name: 'Eclipse', votes: 6 },
{ id: 5, name: 'Fure of Dracula', votes: 2 }
];
let maxGame = games.reduce((max, game) => max.votes > game.votes ? max : game);
agent.add(`${maxGame}`);
}
You can simply find the maximum element by iterating over the array.
let games = [
{ id: 1, name: 'Star Wars: Imperial Assault', votes: 3},
{ id: 2, name: 'Game of Thrones: Second Edition', votes: 4 },
{ id: 3, name: 'Merchans and Marauders', votes: 5 },
{ id: 4, name: 'Eclipse', votes: 6 },
{ id: 5, name: 'Fure of Dracula', votes: 2 }
];
maxElement = -Infinity;
element = null
for (const game of games) {
if (game.votes > maxElement) {
maxElement = game.votes;
element = game;
}
}
console.log(element)
The issue is that maxGame is an object. Using your example, that object will be
{ id: 4, name: 'Eclipse', votes: 6 }
But agent.add() is expecting to send back a string. The default "string" form of an object is "[object Object]", as you've seen.
You probably want to return something that makes more sense when displayed or read aloud, so it might make more sense for that line to be something like
agent.add(`The winner, with ${maxElement.votes} votes, is ${maxElement.name}.`)
which, given the example, would say something like
The winner, with 6 votes, is Eclipse.

Add property from one array into another array with the same key

Instead of explaining the problem in words, I've just made a quick visual representation below.
Say I have the following array:
let arr1 = [
{
id: 1,
someKey: someValue
},
{
id: 2,
someKey: someValue
},
]
and another array:
let arr2 = [
{
id: 1,
numberOfItems: 10
},
{
id: 2,
numberOfItems: 20
},
]
How would I create the following array?
let result = [
{
id: 1,
someKey: someValue,
numberOfItems: 10
},
{
id: 2,
someKey: someValue,
numberOfItems: 10
},
]
So as you can see, both arrays have the same id value. I want to take numberOfItems: 10 from the second array and place it into the first array under the same id.
Note: the two ids are completely different, have different properties and length. The only similarity is the id
You could first create a map with id as key and then combine the objects This would solve the problem in O(n):
let arr1 = [
{
id: 1,
someKey: 3
},
{
id: 2,
someKey: 6
},
];
let arr2 = [
{
id: 1,
numberOfItems: 10
},
{
id: 2,
numberOfItems: 20
},
];
let arr2Map = arr2.reduce((acc, curr) => {
acc[curr.id] = curr
return acc;
}, {});
let combined = arr1.map(d => Object.assign(d, arr2Map[d.id]));
console.log(combined);
let arr1 = [
{
id: 1,
someKey: 3
},
{
id: 2,
someKey: 6
},
];
let arr2 = [
{
id: 1,
numberOfItems: 10
},
{
id: 2,
numberOfItems: 20
},
];
let idToNumberOfItem = {};
arr2.forEach(({id, numberOfItems})=> idToNumberOfItem[id]=numberOfItems)
arr1.forEach((item)=> item['numberOfItems'] = idToNumberOfItem[item.id])
console.log(arr1);

How to avoid duplicate objects from two arrays after filter using java script

i have two arrays ( busns and pc ) i want to check pc array -> pcid is match with busns array -> pcid after match i want to return pcname. final output is comming but i want to avoid duplicate. thanks in advance
please check my attempt in jsfiddle
const busns = [
{
id:1,
shopname:'New trend',
pcid:1
},
{
id:2,
shopname:'Latest Beauty',
pcid:2
},
{
id:3,
shopname:'Mens Style',
pcid:1
},
{
id:4,
name:'Fabulook',
pcid: 1
},
{
id:4,
name:'New cut',
pcid: 2
}
]
const pc = [
{
pcid:1,
pcname: 'collection1'
},
{
pcid:2,
pcname: 'collection2'
},
{
pcid:3,
pcname: 'collection3'
},
{
pcid:4,
pcname: 'collection4'
}
]
My code :
busns.map(busns => {
return pc.filter( p => {
return busns.pcid == p.pcid
}).map(data => {
console.log(data.pcname)
})
})
expected output while using console :
collection1
collection2
As commented, you could use this:
var ids = busns.map(x=>x.pcid); pc.filter(x=> ids.includes(x.pcid))
Your code:
What you are doing is,
Looping on business array to get current PC id.
Then you use this ID to filter out from PC's list and then use map to get name.
Now the issue with your code is, since you are looping on busns array, you are essentially printing the name of PC for every id.
const busns = [{ id: 1, shopname: 'New trend', pcid: 1 }, { id: 2, shopname: 'Latest Beauty', pcid: 2 }, { id: 3, shopname: 'Mens Style', pcid: 1 }, { id: 4, name: 'Fabulook', pcid: 1 }, { id: 4, name: 'New cut', pcid: 2 } ]
const pc = [{ pcid: 1, pcname: 'collection1' }, { pcid: 2, pcname: 'collection2' }, { pcid: 3, pcname: 'collection3' }, { pcid: 4, pcname: 'collection4' } ]
busns.map(busns => {
return pc.filter(p => {
return busns.pcid == p.pcid
}).map(data => {
console.log(data.pcname)
})
})
Solution from comment:
Instead of nested looping structure, what you can do is,
Create a list of pcids. This will help you know if pc is traded.
Loop over pc array. Trades can be many but product will be finite and less in number. Use this to get a filtered list of products that are in busns.
Now loop over this filtered array and retrieve names. This part was not covered in comment.
const busns = [{ id: 1, shopname: 'New trend', pcid: 1 }, { id: 2, shopname: 'Latest Beauty', pcid: 2 }, { id: 3, shopname: 'Mens Style', pcid: 1 }, { id: 4, name: 'Fabulook', pcid: 1 }, { id: 4, name: 'New cut', pcid: 2 } ]
const pc = [{ pcid: 1, pcname: 'collection1' }, { pcid: 2, pcname: 'collection2' }, { pcid: 3, pcname: 'collection3' }, { pcid: 4, pcname: 'collection4' } ]
var ids = busns.map(x=>x.pcid);
var pcNames = pc
.filter(x=> ids.includes(x.pcid))
.map(x=> x.pcname);
console.log(pcNames)
Preferred solution:
One issue with above approaches is extra iterations and duplicate pcid in list. So instead of using functions like .map + .filter, we can use .reduce and create unique list. This will keep iterations minimum.
Create a hashMap with keys as pcid and value as true. This will create a unique id map.
Now loop over pc array and check if current id is present in this object ot not. If present, push name. If not, continue.
I would suggest you to use this approach as this should be more performant. Using .map + .filter + .indexOf can be expensive for huge arrays.
const busns = [{ id: 1, shopname: 'New trend', pcid: 1 }, { id: 2, shopname: 'Latest Beauty', pcid: 2 }, { id: 3, shopname: 'Mens Style', pcid: 1 }, { id: 4, name: 'Fabulook', pcid: 1 }, { id: 4, name: 'New cut', pcid: 2 } ]
const pc = [{ pcid: 1, pcname: 'collection1' }, { pcid: 2, pcname: 'collection2' }, { pcid: 3, pcname: 'collection3' }, { pcid: 4, pcname: 'collection4' } ]
var ids = busns.reduce((acc, cur) => acc[cur.pcid] = true && acc, {});
var pcNames = pc.reduce((acc, cur) => {
if(ids[cur.pcid]) {
acc.push(cur.pcname);
}
return acc;
}, [])
console.log(pcNames)
Something like this.
pc.filter(p => busns.map(busns => busns.pcid).includes(p.pcid)).forEach(data => console.log(data.pcname));

How union arrays with validate only one property

Joining of Arrays.
I'm in need of running a "Join Array" objects, but, I need duplicated objects to be removed, see:
Example
var objArray1 = [
{ Id: 1, Name: 'João', Order: 2 },
{ Id: 2, Name: 'Pedro', Order: 5 }
];
var objArray2 = [
{ Id: 2, Name: 'Pedro', Order: 6 },
{ Id: 3, Name: 'Manoel', Order: 9 }
];
Actual code:
var result = _.union(objArray1,objArray2);
=> [
{ Id: 1, Name: 'João', Order: 2 },
{ Id: 2, Name: 'Pedro', Order: 5 },
{ Id: 2, Name: 'Pedro', Order: 6 },
{ Id: 3, Name: 'Manoel', Order: 9 }
];
I need this result:
[
{ Id: 1, Name: 'João', Order: 2 },
{ Id: 2, Name: 'Pedro', Order: 5 },
{ Id: 3, Name: 'Manoel', Order: 9 }
];
Basic I need join arrays with filter the one property, I need is possible with For but I would like a better solution
use underscore unique function as follows
var result = _.uniq(_.union(objArray1, objArray2), false, function(item){ return item.Id; });
not 100% sure if the false should be true
or, as seems to be a trend on SO - the sexy ES2015 version
var result = _.uniq(_.union(objArray1, objArray2), false, item => item.Id);

Categories

Resources