Filter complex array by another array - javascript

let array1 = [
{
id: 1,
genres: [
{ id: 4, title: "qqqq" },
{ id: 9, title: "zzzz" },
{ id: 8, title: "eeee" },
],
},
{
id: 2,
genres: [
{ id: 2, title: "qwert" },
{ id: 4, title: "asdf" },
{ id: 5, title: "zxxcc" },
],
},
];
let array2 = [6, 8];
I need to filter array1 if genre id exists in array2.
So in output I should have only first element of array1.
How to do that?

You can use a combination of filter, some and includes:
let array1 = [{id:1,genres:[{id:4,title:"qqqq" },{id:9,title:"zzzz"},{id:8,title:"eeee" }]},
{id:2,genres:[{id:2,title:"qwert"},{id:4,title:"asdf"},{id:5,title:"zxxcc"}]}];
let array2 = [6, 8];
let result = array1.filter(({genres}) => genres.some(({id}) => array2.includes(id)));
console.log(result);

Use the filter function.
One way to do it:
let result = array1.filter(el => {
let output = false;
el.genres.forEach( genre => {
if (array2.includes(genre.id))
output = true;
});
return output;
});

Related

Naive approach to summarize array of objects?

I faced a challenge where I needed to summarize an array of objects by the object's keys. I found a solution, but I can't shake off the feeling, that my approach is pretty naive:
const objArr = [
{ id: 1, val: "🍊" },
{ id: 1, val: "🍇" },
{ id: 1, val: "🍎" },
{ id: 2, val: "🥦" },
{ id: 2, val: "🌽" },
{ id: 2, val: "🌶" },
];
let tempArr = [];
let uniqueIdArr = [];
let sortedArr = [];
objArr.forEach((obj) => {
tempArr.push(obj.id);
uniqueIdArr = [...new Set(tempArr)];
});
uniqueIdArr.forEach((uniqueId) => {
let arr = [];
objArr.forEach((obj) => {
if (obj.id == uniqueId) {
arr.push(obj.val);
}
});
sortedArr.push({
id: uniqueId,
vals: arr,
});
});
console.log(sortedArr);
// Output: [{ id: 1, vals: [ '🍊', '🍇', '🍎' ] }, { id: 2, vals: [ '🥦', '🌽', '🌶' ] }]
Maybe there is something I don't know about JavaScript's array methods yet? Is this approach totally wrong? Is there another way, so that I could reduce the code and make it more elegant?
So many questions...
Any hint or explanation would be much appreciated. 🙈
Thanks in advance
J.
you can use Array.prototype.reduce to make your code bit shorter:
const objArr = [
{ id: 1, val: "🍊" },
{ id: 1, val: "🍇" },
{ id: 1, val: "🍎" },
{ id: 2, val: "🥦" },
{ id: 2, val: "🌽" },
{ id: 2, val: "🌶" },
];
let result = objArr.reduce((acc,e) => {
let idx = acc.findIndex(s => s.id === e.id)
if(idx > -1){
acc[idx].vals.push(e.val)
}
else{
acc.push({id:e.id,vals:[e.val]})
}
return acc
},[])
console.log(result)
Your ideas are good and explicit, but far from being optimal.
const objArr = [
{ id: 1, val: "🍊" },
{ id: 1, val: "🍇" },
{ id: 1, val: "🍎" },
{ id: 2, val: "🥦" },
{ id: 2, val: "🌽" },
{ id: 2, val: "🌶" },
];
const idValMap = new Map();
objArr.forEach(o=>{
let vals = idValMap.get(o.id);
if(!vals){
vals = [];
idValMap.set(o.id,vals);
}
vals.push(o.val);
});
console.log(Array.from(idValMap.entries()));
You can do most of it in just one loop. Take the key, check if you saw it already, if not initialize. That's it
This solution probably isn't much better but it is does use less code:
const objArr = [
{ id: 1, val: "🍊" },
{ id: 1, val: "🍇" },
{ id: 1, val: "🍎" },
{ id: 2, val: "🥦" },
{ id: 2, val: "🌽" },
{ id: 2, val: "🌶" },
];
let sortedArr = [];
objArr.forEach((item) => {
const exists = sortedArr.filter(i => i.id === item.id).length; // Check to see if we've already added an item with this ID
if (!exists) {
const matches = objArr.filter(i => i.id == item.id); // get all items with this ID
sortedArr.push({
id: item.id,
vals: matches.map(m => m.val) // We only care about the val property
});
}
});
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for informationa bout .map() and .filter() respectively

What is the most efficient way to iterate between two arrays to find matched values?

I need to find objects in array by matching array of ids. Array of ids can be longer or equal to length of array of persons. I made it with forEach loop of persons array and inside used includes method to find matched id but not sure that it is the good approach. Is there a way to optimize searching algorithm?
const ids = [1, 4, 9, 7, 5, 3];
const matchedPersons = [];
const persons = [
{
id: 1,
name: "James"
},
{
id: 2,
name: "Alan"
},
{
id: 3,
name: "Marry"
}
];
persons.forEach((person) => {
if (ids.includes(person.id)) {
matchedPersons.push(person);
}
});
console.log(matchedPersons);
codesanbox
You could take a Set with O(1) for the check.
const
ids = [1, 4, 9, 7, 5, 3],
persons = [{ id: 1, name: "James" }, { id: 2, name: "Alan" }, { id: 3, name: "Marry" }],
idsSet = new Set(ids),
matchedPersons = persons.filter(({ id }) => idsSet.has(id));
console.log(matchedPersons);
you better use filter. it does exactly what it is meant to do:
const ids = [1, 4, 9, 7, 5, 3];
const persons = [
{
id: 1,
name: "James"
},
{
id: 2,
name: "Alan"
},
{
id: 3,
name: "Marry"
}
];
const matchedPersons = persons.filter(({id}) => ids.includes(id))
console.log(matchedPersons)
you can use Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
const ids = [1, 4, 9, 7, 5, 3];
const matchedPersons = [];
const persons = [
{
id: 1,
name: "James"
},
{
id: 2,
name: "Alan"
},
{
id: 3,
name: "Marry"
}
];
const personsMap = new Map()
persons.forEach((person) => {
personsMap.set(person.id, person)
});
persons.forEach((person) => {
if (personsMap.has(person.id)) {
matchedPersons.push(personsMap.get(person.id));
}
});
console.log(matchedPersons);

JavaScript - Changing the value of object literals

guys!
Basically I want to replace the object literal "title" value of all objects within arr2 with each of the elements within arr1.
const arr1 = ['first', 'second', 'third']
const arr2 = [
{
id: 1,
title: 'hello'
},
{
id: 2,
title: 'world'
},
{
id: 3,
title: ' 🌎'
}
]
For the end result to be this:
const final = [
{
id: 1,
title: 'first'
},
{
id: 2,
title: 'second'
},
{
id: 3,
title: 'third'
}
]
I really don't understand how I could do such a thing, I am totally stranded at this stage.
Have a great day!
You can clone your original object (to avoid mutation) and then iterates with a for loop replacing every object inside the array:
const arr1 = ['first', 'second', 'third']
const arr2 = [
{
id: 1,
title: 'hello'
},
{
id: 2,
title: 'world'
},
{
id: 3,
title: ' 🌎'
}
]
let result = JSON.parse(JSON.stringify(arr2));
for(let i = 0; i < arr2.length; i++){
result[i].title = arr1[i]
}
console.log(result)
You can do like as follows:
arr2.forEach((x,i)=>{x.title=arr1[i]})
x : is element
i : is index
Example:
var arr1 = ['first', 'second', 'third']
var arr2 = [
{
id: 1,
title: 'hello'
},
{
id: 2,
title: 'world'
},
{
id: 3,
title: ' 🌎'
}
]
arr2.forEach((x,i)=>{x.title=arr1[i]})
console.log(arr2)
if you don't want to modify existing object you can use map method
arr2.map((x,i)=>{
return {id:x.id,title:arr1[i]}
})
Example:
var arr1 = ['first', 'second', 'third']
var arr2 = [
{
id: 1,
title: 'hello'
},
{
id: 2,
title: 'world'
},
{
id: 3,
title: ' 🌎'
}
]
var result = arr2.map((x,i)=>{
return {id:x.id,title:arr1[i]}
})
console.log(result)
arr2.map((v, k) =>{
v.title = arr1[k]
});
You set the title of each item with the string in the arr1 which is at the same index.

How to sort an array of objects using another array for reference?

i want to sort an array of objects having id each object using another array that only has the ids, for example:
object = [
{id: 2, name: carlos},
{id: 1, name: maria},
{id: 4, name: juan},
{id: 3, name: pepe}, //this is the array that i want to be sorted or create a copy to return it
]
[1,2,3,4,5] //this is the array that i will use as reference to sort the first one
the final result should be:
object = [
{id: 1, name: maria},
{id: 2, name: carlos},
{id: 3, name: pepe},
{id: 4, name: juam}, //this is the array that i want to be sorted or create a copy to return it
]
im using two maps, but im always getting and array with undefined:
array_to_be_sorted.map((objects) => {
array_reference.map((id) => {
if (objects.id === id) {
return {...objects}
}
}
}
im using map cause think is the best way for bigs array, because im building a music player, so dont know how many tracks the does the user has
You could use Array.prototype.sort() method to get the result.
const data = [
{ id: 2, name: 'carlos' },
{ id: 1, name: 'maria' },
{ id: 4, name: 'juan' },
{ id: 3, name: 'pepe' },
];
const order = [1, 2, 3, 4, 5];
data.sort((x, y) => order.indexOf(x.id) - order.indexOf(y.id));
console.log(data);
Another solution using Map Object which is faster than the first one.
const data = [
{ id: 2, name: 'carlos' },
{ id: 1, name: 'maria' },
{ id: 4, name: 'juan' },
{ id: 3, name: 'pepe' },
];
const order = [1, 2, 3, 4, 5];
const map = new Map();
order.forEach((x, i) => map.set(x, i));
data.sort((x, y) => map.get(x.id) - map.get(y.id));
console.log(data);
Why not just use Array.prototpye.sort()? It's easy and fast.
const pre = document.querySelector('pre');
let object = [
{id: 2, name: 'carlos'},
{id: 1, name: 'maria'},
{id: 4, name: 'juan'},
{id: 3, name: 'pepe'}
];
const criteria = [1,2,3,4,5];
pre.innerText = 'object:' + JSON.stringify(object, null, 2) + '\n\n';
object.sort((a, b) => {
return criteria[a.id] - criteria[b.id];
});
pre.innerText += 'sorted object:' + JSON.stringify(object, null, 2);
Sort an array using criteria from a second array:
<pre></pre>
You can take advantage of Schwartzian transform and sort data based on another array.
const data = [ { id: 2, name: 'carlos' }, { id: 1, name: 'maria' }, { id: 4, name: 'juan' }, { id: 3, name: 'pepe' }, ],
order = [4, 2, 3, 1, 5],
result = data.map(o => {
const index = order.indexOf(o.id);
return [index, o];
})
.sort((a, b) => a[0] - b[0])
.map(([, o]) => o);
console.log(result);

How to filter an array of object with an array of numbers

Given an array of objects arr1 how can I filter out to a new array the objects that do not have a property equal to any value in the array of numbers arr2
const arr1 = [
{
key: 1,
name: 'Al'
},
{
key: 2,
name: 'Lo'
},
{
key: 3,
name: 'Ye'
}
];
const arr2 = [2, 3]
// Failed attempt
const newArr = arr1.filter(obj1 => arr2.some(num1 => num1 !== obj1.key))
console.log(newArr)
// Expected: [{ key: 1, name: 'Al' }]
// Received: [
// { key: 1, name: 'Al' },
// { key: 2, name: 'Lo' },
// { key: 3, name: 'Ye' }
// ]
Using your syntax:
You have to match on the somein case it's the same and not different. Then if it matches, do not keep the value.
const arr1 = [
{
key: 1,
name: 'Al',
},
{
key: 2,
name: 'Lo',
},
{
key: 3,
name: 'Ye',
},
];
const arr2 = [2, 3];
const newArr= arr1.filter(x => !arr2.some(y => y === x.key));
console.log(newArr);
Alternative syntax below :
const arr1 = [{
key: 1,
name: 'Al',
},
{
key: 2,
name: 'Lo',
},
{
key: 3,
name: 'Ye',
},
];
const arr2 = [2, 3];
const newArr = arr1.filter(({
key,
}) => !arr2.some(y => y === key));
console.log(newArr);
That said, you should be using Array.includes() like some ppl answered. It's simplier for the same outcome
const arr1 = [{
key: 1,
name: 'Al',
},
{
key: 2,
name: 'Lo',
},
{
key: 3,
name: 'Ye',
},
];
const arr2 = [2, 3];
const newArr = arr1.filter(({
key,
}) => !arr2.includes(key));
console.log(newArr);
You can do this
const newArr = arr1.filter(obj => !arr2.includes(obj.key));
This will work for you:
const arr1 = [
{
key: 1,
name: 'Al'
},
{
key: 2,
name: 'Lo'
},
{
key: 3,
name: 'Ye'
}
];
const arr2 = [2, 3]
const filtered = arr1.filter(val => !arr2.includes(val.key))
console.log(filtered)
:)
For situations like this Set is also very cool (and for big arrays more performant):
const arr1 = [
{
key: 1,
name: 'Al'
},
{
key: 2,
name: 'Lo'
},
{
key: 3,
name: 'Ye'
}
];
const arr2 = [2, 3]
const arr2Set = new Set(arr2);
const newArr = arr1.filter(obj1 => !arr2Set.has(obj1.key))
console.log(newArr)
You can use indexOf like this:
const newArr = arr1.filter(obj => arr2.indexOf(obj.key) > -1);
You need to filter the arr1 when arr1 element does not exist in arr2, so I think it could be better to use indexOf() like this
const newArr = arr1.filter(obj1 => arr2.indexOf(obj1.key) === -1)
if the element does not exist in arr2 it will return -1 which what you need.

Categories