How to find third values comparing two values in javascript? - javascript

Here I have two arrays array1 and array2 I want to find ids from array1 which array1's names matched with array2 values how to find ids in javascript ?
array1:
[ {id: 1, name: "Hindi"}
{id: 2, name: "English"}
{id: 3, name: "French"}
{id: 4, name: "Russian"}
{id: 5, name: "Urdu"}
{id: 6, name: "Japanese"}
]
array2:
["Hindi", "Russian", "Urdu"]
I tried this code
console.log(array1.find(x => x.name === array2).id;

You can use filter() to get objects whose names are in the array.Then use map() to convert array of values to array of ids.
In your code you are comparing the string with array x.name === array2. You should use includes()
let arr = [ {id: 1, name: "Hindi"}, {id: 2, name: "English"}, {id: 3, name: "French"}, {id: 4, name: "Russian"}, {id: 5, name: "Urdu"}, {id: 6, name: "Japanese"} ]
let lang = ["Hindi", "Russian", "Urdu"];
let res = arr.filter(x => lang.includes(x.name)).map(x => x.id);
console.log(res)

You should use filter method in combination with map and destructuring
let arr1 = [ {id: 1, name: "Hindi"}, {id: 2, name: "English"}, {id: 3, name: "French"}, {id: 4, name: "Russian"}, {id: 5, name: "Urdu"}, {id: 6, name: "Japanese"} ], arr2 = ["Hindi", "Russian", "Urdu"];
console.log(arr1.filter(({name}) => arr2.includes(name)).map(({id}) => id));

Try this:
var a = [{
id: 1,
name: "Hindi"
}, {
id: 2,
name: "English"
}, {
id: 3,
name: "French"
}, {
id: 4,
name: "Russian"
}, {
id: 5,
name: "Urdu"
}, {
id: 6,
name: "Japanese"
}]
var b = ["Hindi", "Russian", "Urdu"];
var c = a.filter(function(i){
return b.indexOf(i.name)>-1;
});
console.log(c); // New Array with filtered values

This will work too :)
var a1 = [{
id: 1,
name: "Hindi"
}, {
id: 2,
name: "English"
}, {
id: 3,
name: "French"
}, {
id: 4,
name: "Russian"
}, {
id: 5,
name: "Urdu"
}, {
id: 6,
name: "Japanese"
}]
var a2 = ["Hindi", "Russian", "Urdu"];
var filter = a1.filter(function(i) {
return a2.indexOf(i.name) > -1;
}).map(function(obj) {
return obj.id;
});;
console.log(filter);

Related

Combine Promises Arrays, in Only One JavaScript

I am using some promises to get information, but in this case I have a principal array, my idea is:
For loop to each company id to get payment
For loop to each payment array id to get employers
Show in one array the results
MY CODE
var data = [
{
id: 1,
company: 'A'
},
{
id: 2,
company: 'B'
},
{
id: 3,
company: 'C'
}
]
var p1 = [];
for(var i =0; i < data.length; i++){
p1.push(global.get_payments(data, i));
}
Promise.all(p1)
.then(response_p1 => {
//I added the response in same structure see response_p1
for(var i =0; i < response_p1.length; i++){
var employers = [];
for(var x =0; x < response_p1[i].payment.length; x++){
employers.push(global.get_employers(response_p1[i].payment, x));
}
Promise.all(employers)
.then(response_employers => {
//I added the response into payment array
//HOW CAN I COMBINE IN ONLY ONE ARRAY?
}).catch(err => {
console.log(err)
})
}
}).catch(err => {
console.log(err)
})
response_p1 = [
{
id: 1,
company: A',
payment: [
{id: 4}
]
},
{
id: 2,
company: 'B',
payment: [
{id: 5}
]
},
{
id: 3,
company: 'C',
payment: [
{id: 6}
]
}
]
response_employers = [
{
id: 4,
employer_list: [
{id: 1, name: 'Carles'},
{id: 2, name: 'Max'}
]
}
]
[
{
id: 5,
employer_list: [
{id: 3, name: 'Dania'},
{id: 4, name: 'Luis'}
]
}
]
[
{
id: 6,
employer_list: [
{id: 5, name: 'Lenny'},
{id: 6, name: 'Hommer'}
]
}
]
RESULT EXPECTED [
{
id: 4,
employer_list: [
{id: 1, name: 'Carles'},
{id: 2, name: 'Max'}
]
},
{
id: 5,
employer_list: [
{id: 3, name: 'Dania'},
{id: 4, name: 'Luis'}
]
},
{
id: 6,
employer_list: [
{id: 5, name: 'Lenny'},
{id: 6, name: 'Hommer'}
]
}
]
my problem is that I am getting 3 array and I want that response_employers should be in only one array, How can I solve that

How to compare two array and create new one with different key value pair?

I have two array and need to take specific key value pair and assign to third one array and it will also take care of duplication entry.
First Array :
[
{id: 2, name: "HSBC", status: "YES"},
{id: 3, name: "Morgan Stanley", status: "Pending"}
]
Second Array:
[
{id: 1, name: "Deutsche Bank", category: "EQUITIES"},
{id: 2, name: "HSBC", category: "EQUITIES"},
{id: 3, name: "Morgan Stanley", category: "EQUITIES"},
{id: 4, name: "Credit Suisse", category: "EQUITIES"},
]
From above two arrays I need to take name and status field and create the new array. Like below:
[
{ brokerName: "HSBC", statis: "YES"},
{ brokerName: "Morgan Stanley", statis: "Pending"},
{ brokerName: "Deutsche Bank", statis: ""},
{ brokerName: "Credit Suisse", statis: ""},
]
TIA.
Stackblitz
let arr1 = [{id: 1, name: "name", status: "YES"}];
let arr2 = [{id: 1, name: "name", category: "EQUITIES"}];
let sumbit = [];
for (let i=0; i<arr1.length; i++) {
let is_there = false;
for (let j=0; j<arr2.length; j++) {
if (arr1[i].name == arr[j].name) {
submit.push({brokerName: arr1[i].name, statis: arr1[i].status});
is_there = true;
}
}
if (!is_there) submit.push({brokerName: arr1[i].name, statis: ""})
}
You could just write the code :D
Here is an example:
const array1 = [
{id: 2, name: "HSBC", status: "YES"},
{id: 3, name: "Morgan Stanley", status: "Pending"}
];
const array2 = [
{id: 1, name: "Deutsche Bank", category: "EQUITIES"},
{id: 2, name: "HSBC", category: "EQUITIES"},
{id: 3, name: "Morgan Stanley", category: "EQUITIES"},
{id: 4, name: "Credit Suisse", category: "EQUITIES"},
];
// returns { name, status } recoreds from any number of arrays
function getBrokersDataFromArrays(...arrays) {
const allBrokers = new Map();
// collect all the available data for all the brokers
arrays.flat().forEach(broker => {
if (allBrokers.has(broker.name)) {
allBrokers.set(broker.name, { ...allBrokers.get(broker.name), ...broker });
} else {
allBrokers.set(broker.name, broker);
}
});
// return only { name, status } fields from the collected brokers
return Array.from(allBrokers.values()).map(broker => (
{ name: broker.name, status: broker.status }
));
}
const brokersData = getBrokersDataFromArrays(array1, array2);
console.log(brokersData);
let array1 = [
{id: 2, name: "HSBC", status: "YES"},
{id: 3, name: "Morgan Stanley", status: "Pending"}
]
let array2 = [
{id: 1, name: "Deutsche Bank", category: "EQUITIES"},
{id: 2, name: "HSBC", category: "EQUITIES"},
{id: 3, name: "Morgan Stanley", category: "EQUITIES"},
{id: 4, name: "Credit Suisse", category: "EQUITIES"},
]
// filter data which are present into both array
const result1 = array1.filter(o => array2.some(({ name }) => o.name === name));
// filter data which are present into array1 but not into array2
const result2 = array1.filter((o1) => {
return !array2.some((o2) => {
return o1.name === o2.name;
});
})
// filter data which are present into array2 but not into array1
const result3 = array2.filter((o1) => {
return !array1.some((o2) => {
return o1.name === o2.name;
});
})
// concat all result
let result = (result1.concat(result2)).concat(result3)
let finalArr = []
for (let obj of result) {
finalArr.push({ brokerName: obj.name, status: obj.status ? obj.status : "" })
}

Arrange list of objects by another list of objects, sort by id

Hi i'm trying to organize this data, i can arrange this product list by index of userSettings.categories array, i need also to sort the products by id like the sortedProducts property, this is what i've been trying for now, thanks in advance community.
let products = [
{id: 1, name: 'Brasilian', category: 'cofee'},
{id: 2, name: 'Colombian', category: 'cofee'},
{id: 3, name: 'Apple', category: 'fruit'},
{id: 4, name: 'Strawberry', category: 'fruit'},
{id: 5, name: 'Banana', category: 'fruit'},
{id: 6, name: 'Pepper', category: 'spices'},
{id: 7, name: 'Salt', category: 'spices'}
]
let userSettings = {
categories: [
{name: 'fruit', sortedProducts: [4, 3, 5]},
{name: 'spices', sortedProducts: [6, 7]},
{name: 'cofee', sortedProducts: [2, 1]},
]
}
let arrangedProducts = userSettings.categories.map(c => products.filter(o => o.category == c.name));
console.log(arrangedProducts);
expectedOutput = [
[
{id: 4, name: 'Strawberry', category: 'fruit'},
{id: 3, name: 'Apple', category: 'fruit'},
{id: 5, name: 'Banana', category: 'fruit'}
],
[
{id: 6, name: 'Pepper', category: 'spices'},
{id: 7, name: 'Salt', category: 'spices'}
],
[
{id: 2, name: 'Colombian', category: 'cofee'},
{id: 1, name: 'Brasilian', category: 'cofee'}
]
];
console.log(expectedOutput);
You can try
let arrangedProducts = userSettings.categories.map(
c => c.sortedProducts.map(
id => products.find(product => product.id === id)
)
);
Or if you have a lot of items in the future and want it to run faster, you can use hash table
const hashProduct = products.reduce((a, b) => ({...a, [b.id]: b}), {});
console.log(
userSettings.categories.map(
c => c.sortedProducts.map(id => hashProduct[id])
)
);
Try:
let products=[{id:1,name:"Brasilian",category:"cofee"},{id:2,name:"Colombian",category:"cofee"},{id:3,name:"Apple",category:"fruit"},{id:4,name:"Strawberry",category:"fruit"},{id:5,name:"Banana",category:"fruit"},{id:6,name:"Pepper",category:"spices"},{id:7,name:"Salt",category:"spices"}]
let userSettings={categories:[{name:"fruit",sortedProducts:[4,3,5]},{name:"spices",sortedProducts:[6,7]},{name:"cofee",sortedProducts:[2,1]}]};
let result = []
userSettings.categories.forEach((e) => { let arr = []; e.sortedProducts.forEach(f => arr.push(products.filter(g => g.id == f))); result.push(arr) })
console.log(result);
You can sort by the indexOf in the sortedProducts array
userSettings.categories
.map(c => products
.filter(o => o.category == c.name)
.sort((a, b) =>
c.sortedProducts.indexOf(a.id) - c.sortedProducts.indexOf(b.id)))
let products = [{
id: 1,
name: 'Brasilian',
category: 'cofee'
},
{
id: 2,
name: 'Colombian',
category: 'cofee'
},
{
id: 3,
name: 'Apple',
category: 'fruit'
},
{
id: 4,
name: 'Strawberry',
category: 'fruit'
},
{
id: 5,
name: 'Banana',
category: 'fruit'
},
{
id: 6,
name: 'Pepper',
category: 'spices'
},
{
id: 7,
name: 'Salt',
category: 'spices'
}
]
let userSettings = {
categories: [{
name: 'fruit',
sortedProducts: [4, 3, 5]
},
{
name: 'spices',
sortedProducts: [6, 7]
},
{
name: 'cofee',
sortedProducts: [2, 1]
},
]
}
let expectedOutput = userSettings.categories.map(c => products.filter(o => o.category == c.name).sort((a, b) => c.sortedProducts.indexOf(a.id) - c.sortedProducts.indexOf(b.id)));
console.log(expectedOutput);

Count the number of items in each category within a JavaScript object

I have an array containing several hundred objects, each of which has a category. I wish to return an object that lists out the categories with a count of the number of items for each category.
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
How would I loop through the object and create a new object that contains just the two categories and how many of each per category?
Desired output:
{vehicle: 4, animal: 3}
Code:
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const final = {};
arr.forEach((v) => {
const tst = v.category;
console.log(tst);
if (tst in final){
console.log('found one');
}
});
//console.log(final);
You can use reduce
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const categories = arr.reduce((acc, cur) => {
acc[cur.category] = (acc[cur.category] || 0) + 1
return acc;
}, {})
console.log(categories)
edit:
Now, after a year a would wrt this like that
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const categories = arr.reduce((acc, cur) => Object.assign(acc, {
[cur.category]: (acc[cur.category] || 0) + 1,
}), {})
console.log(categories)
It looks like the category will always exist, so you don't need to check whether it exists, but what it contains; take what it contains and increment that property on the final object:
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const final = {};
for (const { category } of arr) {
final[category] = (final[category] || 0) + 1;
};
console.log(final);
You have the right idea regarding looping over the array and checking if the category was already encountered. What you're missing is initializing a counter when you find a new category and incrementing it the next time that category is encountered:
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const final = {};
arr.forEach((v) => {
const cat = v.category;
if (cat in final) {
final[cat]++;
} else {
final[cat] = 1;
}
});
console.log(final);
const arr = [
{ id: 1, name: 'ford', category: 'vehicle' },
{ id: 2, name: 'pig', category: 'animal' },
{ id: 3, name: 'dog', category: 'animal' },
{ id: 4, name: 'chev', category: 'vehicle' },
{ id: 5, name: 'cat', category: 'animal' },
{ id: 6, name: 'jeep', category: 'vehicle' },
{ id: 7, name: 'honda', category: 'vehicle' },
]
// this will hold the results
const result = {}
for (const item of arr) {
// we have not encountered such category before
if (result[item.category] === undefined) {
// setting this category to 1
result[item.category] = 1
// we encountered such category before
} else {
// addint +1 to it
result[item.category] += 1
}
}
console.log(result)

How to add object element in array based on condition

I have static array constant of objects something similar to below.
export const EMPLOYEES = [
{
id: 2,
name: ‘John’,
},
{
id: 3,
name: ‘Doe’,
},
{
id: 4,
name: ‘Bull’,
},
{
id: 5,
name: ‘Scott’,
},
];
Now I need to add the last element only based on if some condition is true. Some this like if isAmerican() is true.
Can somebody help me here how to add element based on the condition? Thanks.
You can do it using spread operator:
export const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
... isAmerican() ? [{ id: 6, name: "Jemmy"}] : []
];
You should never modify (or try to modify) a constant. I can see two ways you can do this:
Create a pure function to return a new constant with the new object added to the array
Use a spread operator in the definition of the constant
Option 1: Pure function
function makeNewArray(array, objectToAppend, isAmerican) {
return isAmerican ? [...array, objectToAppend] : array
}
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
}
];
const arrayWithAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "American Frank"}, true);
const arrayWithoutAmerican = makeNewArray(EMPLOYEES, { id: 6, name: "Not American Frank"}, false);
console.log(arrayWithAmerican);
console.log(arrayWithoutAmerican);
Option 2: Spread operator
function isAmerican(){
// generic code here.
return true;
}
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
... isAmerican() ? [{ id: 6, name: "American Frank"}] : []
];
If the condition will be fulfilled, simply push an object to your EMPLOYEES array:
let isAmerican = true;
const EMPLOYEES = [
{
id: 2,
name: "John",
},
{
id: 3,
name: "Doe",
},
{
id: 4,
name: "Bull",
},
{
id: 5,
name: "Scott",
},
];
if(isAmerican) {
EMPLOYEES.push({
id: 6,
name: "Frank"
})
}
console.log(EMPLOYEES)
Fiddle: https://jsfiddle.net/rqx35pLz/

Categories

Resources