I have two arrays of objects.Where each object has different properties, Like this
let array1=[
{id:121122,name:"Matt Jeff"},
{id:121123,name:"Philip Jeff"},
{id:121124,name:"Paul Jeff"}]
let array2=[
{owner_id:121122,id:1211443,value:18},
{owner_id:121127,id:1211428,value:22}]
How can I check if the owner_id in the array2 is equal to the id in array1 then return the new array like this
let newArray=[
{owner_id:121122,id:1211443,value:18}
]
Where the owner_id in array2 is equal to the id in array1.
If I correctly understand what you need, you could do like this:
let array1 = [{
id: 121122,
name: "Matt Jeff"
}, {
id: 121123,
name: "Philip Jeff"
}, {
id: 121124,
name: "Paul Jeff"
}
]
let array2 = [{
owner_id: 121122,
id: 1211443,
value: 18
}, {
owner_id: 121127,
id: 1211428,
value: 22
}
]
const result = array2.filter(({ owner_id }) => array1.some(({ id }) => id === owner_id));
console.log(result);
You could try with nested for like:
let array1=[
{id:121122,name:"Matt Jeff"},
{id:121123,name:"Philip Jeff"},
{id:121124,name:"Paul Jeff"}]
let array2=[
{owner_id:121122,id:1211443,value:18},
{owner_id:121127,id:1211428,value:22}];
let result = [];
for(let i = 0; i < array1.length; i++) {
for(let j = 0; j < array2.length; j++) {
if (array1[i].id === array2[j].owner_id) {
result.push(array2[j]);
}
}
}
console.log(result)
EFFICIENT WAY: Using Set and filter
O(m) - Iterating on array1 and Storing the id in Set
O(n) - Iterating on the array2 and filtering the result which include O(1) to search in Set;
let array1 = [
{ id: 121122, name: "Matt Jeff" },
{ id: 121123, name: "Philip Jeff" },
{ id: 121124, name: "Paul Jeff" },
];
let array2 = [
{ owner_id: 121122, id: 1211443, value: 18 },
{ owner_id: 121127, id: 1211428, value: 22 },
];
const dict = new Set();
array1.forEach((o) => dict.add(o.id));
const result = array2.filter((o) => dict.has(o.owner_id));
console.log(result);
Related
let selectedRow = ["1","2","3"];
let arr = [
{ id:1, name:"eddie" },
{ id:2, name:"jake" },
{ id:3, name:"susan" },
];
Updation on the answer provided by Andy, If you don't want to update the exiting array and want to result in a new array
let selectedRow = ["1", "2"];
let arr = [
{ id: 1, name: "eddie" },
{ id: 2, name: "jake" },
{ id: 3, name: "susan" },
];
const result = arr.filter(item => !selectedRow.includes(item.id.toString()))
console.log(result)
If you want changes in a current array and don't want to store results in a new array (Not the most efficient solution though)
let selectedRow = ["1", "2"];
let arr = [
{ id: 1, name: "eddie" },
{ id: 2, name: "jake" },
{ id: 3, name: "susan" },
];
for (const row of selectedRow) {
const index = arr.findIndex(item => item.id.toString() === row)
if (index !== -1)
arr.splice(index, 1)
}
console.log(arr)
Make sure your selectedRow array is an array of numbers (because your object ids are numbers).
filter over the array of objects and only keep the ones that selectedRow doesn't include.
const arr = [{ id: 1, name: 'eddie' }, { id: 2, name: 'jake' }, { id: 3, name: 'susan' }];
const selectedRow = ['1', '2'].map(Number);
const result = arr.filter(obj => {
return !selectedRow.includes(obj.id);
});
console.log(result);
I have two array of objects (array1, array2). I am trying return final array(as shown below) which eliminates duplicates from array2 but not array1. I am giving priority to array1.
array1 =[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" },
]
array2 =[
{ phone: "2144564", name: "John" },
{ phone: "286456", name: "Mike" },
]
This is something I want as a final result. Remove duplicates from array2 only.
Final Array:
[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" },
{ phone: "286456", name: "Mike" },
]
This is something that I have tried:
for(let i = 0; i < array1.length; i++) {
let name = array1[i].name;
for(let a = 0; i < array2.length; a++) {
let newname = array2[a].name;
if(name !== newname) {
array1.push(
{
phone: array2[a].phone,
name: array2[a].name
});
}
console.log(array1);
}
}
This is the error I get.
"errorType": "TypeError",
"errorMessage": "Cannot read property 'name' of undefined",
You were close to the solution, you can create a Set to contain names of your array1 elements and pushing array1 elements to your result array; subsequently add elements of array2 which names are not contained in your set to your result array :
function removeDuplicates(array1, array2) {
const result = [];
const set = new Set();
for (const elem of array1) {
result.push(elem);
set.add(elem.name);
}
for (const elem of array2) {
if (!set.has(elem.name)) {
result.push(elem);
}
}
return result;
}
const array1 =[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" }
];
const array2 =[
{ phone: "2144564", name: "John" },
{ phone: "286456", name: "Mike" }
];
console.log(JSON.stringify(removeDuplicates(array1, array2)));
you have done a typo mistake in inner for loop condition a < array2.length
Changing the array1 length will results to infinite loop
Every time, when the if(name !== newname) the condition is true, inserting a new object in array1 will results to changing the array1 length.
let array1 =[
{ phone: "07485454", name: "John" },
{ phone: "054554", name: "Ryan" },
]
let array2 =[
{ phone: "2144564", name: "John" },
{ phone: "286456", name: "Mike" },
]
let result = array2.reduce((accumulator, currentItem) =>{
let index = accumulator.findIndex(item => item.name === currentItem.name);
if(index === -1){
accumulator.push(currentItem);
}
return accumulator;
},array1);
console.log(result);
This question already has answers here:
How to add an array of values to a Set
(11 answers)
Closed 3 years ago.
Set only adds 1 copy of an array and I'm not sure why it doesn't keep adding other copies.
The function below takes in an array of trips with the travelers id and another array containing the travelers' ids and names. In this chunk of code,
if(item.type === type){
store.add(...item.travelers);
}
I expected that 123,456 and 789 will be added to the set. However, only 123 and 456 are added. Why doesn't the Set add in the second copy (which would be 456 and 789)?
const travelers = [
{
id: 123,
name: 'John'
},
{
id: 456,
name: 'Raymond'
},
{
id: 789,
name: 'Mary'
},
];
const trip = [
{
type: 'car',
travelers: [123, 456]
},
{
type: 'flight',
travelers: []
},
{
type: 'car',
travelers: [456, 789]
},
];
function determinePeopleForEachTripType(arr, travelers, type){
const result = [];
let store = new Set();
for(let i = 0; i< arr.length; i++){
let item = arr[i];
if(item.type === type){
store.add(...item.travelers);
}
}
store.forEach(eachStore =>{
for(let j = 0; j< travelers.length; j++){
if(eachStore === travelers[j].id){
result.push(travelers[j].name)
}
}
})
return result;
}
determinePeopleForEachTripType(trip, travelers, 'car');
Expected result: Set contains [123, 456, 789]. But actual output is Set contains [123, 456]. What are some possible ways to fix this code?
Set.prototype.add only takes one argument, and that's the one element - you need to iterate through travellers and add each item separately:
item.travelers.forEach(Set.prototype.add, store);
const travelers = [
{
id: 123,
name: 'John'
},
{
id: 456,
name: 'Raymond'
},
{
id: 789,
name: 'Mary'
},
];
const trip = [
{
type: 'car',
travelers: [123, 456]
},
{
type: 'flight',
travelers: []
},
{
type: 'car',
travelers: [456, 789]
},
];
function determinePeopleForEachTripType(arr, travelers, type){
const result = [];
let store = new Set();
for(let i = 0; i< arr.length; i++){
let item = arr[i];
if(item.type === type){
for (let traveler of item.travelers) {
store.add(traveler);
}
}
}
store.forEach(eachStore =>{
for(let j = 0; j< travelers.length; j++){
if(eachStore === travelers[j].id){
result.push(travelers[j].name)
}
}
})
return result;
}
const result = determinePeopleForEachTripType(trip, travelers, 'car');
console.log(result)
If you want to remove more than one object from the first array "arrayOne" which is not present in the second array "arrayTwo". It's just a suggestion the way I do. If you have any other way please let me know.
let arrayOne = [{
id: 1
}, {
id: 2
}, {
id: 3
}]
let arrayTwo = [{
id: 2
},{
id: 3
}]
for (var index = arrayOne.length; index--;) {
if (!arrayTwo.find(y => y.id === arrayOne[index].id)) {
arrayOne.splice(arrayOne.findIndex(z => z.id === arrayOne[index].id), 1)
console.log("After splice", arrayOne)
}
You can also use a Set to store ids of elements of arrayTwo and then filter to extract only those elements of arrayOne that are also present in arrayTwo:
let arrayOne = [{
id: 1
}, {
id: 2
}, {
id: 3
}];
let arrayTwo = [{
id: 2
}];
let arrayTwoSet = new Set(arrayTwo.map(e => e.id));
console.log(arrayOne.filter(e => arrayTwoSet.has(e.id)));
use Array.some() inside Array.filter()
let arrayOne = [{ id: 1 }, { id: 2 }, { id: 3 }] ;
let arrayTwo = [{ id: 2 }];
const result = arrayOne.filter(obj1 => !arrayTwo.some(obj2 => obj1.id === obj2.id));
console.log('final array : ', result);
I have two arrays of objects(arr1 and arr2). I want to select objects from arr1 where arr1.id == arr2.typeId and add to result arr2.Price
var arr1 =
[{"id":20,"name":"name1"},
{"id":24,"name":"name2"},
{"id":25,"name":"name3"},
{"id":28,"name":"name4"},
{"id":29,"name":"name5"}]
var arr2 =
[{"typeId":20,"Price":500},
{"typeId":24,"Price":1100},
{"typeId":28,"Price":1000}]
How can I get the following?
var result =
[{"item":{"id":20,"name":"name1"}, "price":"500"}},
{{"item":{"id":24,"name":"name2"}, "price":"1100"},
{{"item":{"id":28,"name":"name4"}, "price":"1000"}]
var result = arr1.filter(function(obj1){
return arr2.some(function(obj2){
return obj1.id === obj2.typeId;
});
})
You can use reduce() on arr2 and then check if object with same id exists in arr1 with find().
var arr1 =
[{"id":20,"name":"name1"},
{"id":24,"name":"name2"},
{"id":25,"name":"name3"},
{"id":28,"name":"name4"},
{"id":29,"name":"name5"}]
var arr2 =
[{"typeId":20,"Price":500},
{"typeId":24,"Price":1100},
{"typeId":28,"Price":1000}]
var result = arr2.reduce(function(r, e) {
var c = arr1.find(a => e.typeId == a.id)
if(c) r.push({item: c, price: e.Price})
return r
}, [])
console.log(result)
You could create an object without any prototypes with Object.create as hash table and push the new object only if both arrays have a common id.
var arr1 = [{ id: 20, name: "name1" }, { id: 24, name: "name2" }, { id: 25, name: "name3" }, { id: 28, name: "name4" }, { id: 29, name: "name5" }],
arr2 = [{ typeId: 20, Price: 500 }, { typeId: 24, Price: 1100 }, { typeId: 28, Price: 1000 }],
hash = Object.create(null),
result = [];
arr1.forEach(function (a) {
hash[a.id] = a;
});
arr2.forEach(function (a) {
if (hash[a.typeId]) {
result.push({ item: hash[a.typeId], price: a.Price });
}
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another approach, using Array#forEach.
var arr1 = [{id:20,name:"name1"},{id:24,name:"name2"},{id:25,name:"name3"},{id:28,name:"name4"},{id:29,name:"name5"}],
arr2 = [{typeId:20,Price:500},{typeId:24,Price:1100},{typeId:28,Price:1e3}],
result = [];
arr2.forEach(function(v){
var elem = arr1.find(c => c.id == v.typeId); //find corresponding element from the `arr1` array
result.push({item: elem, price: v.Price}); //push an object containing `item` and `price` keys into the result array
});
console.log(result); //reveal the result