Filter Dynamic keys based on input - javascript

I have an array and I need to filter out keys based on an input string. Only OLD_VAL is static, the rest are dynamic. I tried using the variable but it is not bringing that key
let input = VKORG,VTWEG,MATNR;
let arr = [
{
VKORG: 1100,
VTWEG: 10,
MATNR: 12,
RATE: 0.01,
VALUE: 1,
OLD_VAL: 12,
},
{
VKORG: 2100,
VTWEG: 99,
MATNR: 13,
RATE: 0.11,
VALUE: 11,
OLD_VAL: 12,
},
];
Output:
[
{
VKORG: "1100",
VTWEG: 10,
MATNR: "12",
OLD_VAL: 12,
},
{
VKORG: "2100",
VTWEG: 99,
MATNR: "13",
OLD_VAL: 12,
},
];
Code tried
let filterResults = results.map(({ OLD_VAL,input }) => ({ OLD_VAL, input }))

Assuming input is an array of strings, you can use Object.entries and create an object at each iteration consisting of the key-value pairs where keys are obtained from the input.
const input = ['VKORG', 'VTWEG', 'MATNR']
const arr = [{
VKORG: 1100,
VTWEG: 10,
MATNR: 12,
RATE: 0.01,
VALUE: 1,
OLD_VAL: 12,
},
{
VKORG: 2100,
VTWEG: 99,
MATNR: 13,
RATE: 0.11,
VALUE: 11,
OLD_VAL: 12,
}
]
const result = arr.map(el => Object.fromEntries(input.map(key => [key, el[key]]).concat([['OLD_VAL', el.OLD_VAL]])));
console.log(result);
If the input isn't an array of strings but is a string('VKORG,VTWEG,MATNR') then you can split it and use the above logic.
const input = 'VKORG,VTWEG,MATNR';
const inputArr = input.split(',');
const arr = [{
VKORG: 1100,
VTWEG: 10,
MATNR: 12,
RATE: 0.01,
VALUE: 1,
OLD_VAL: 12,
},
{
VKORG: 2100,
VTWEG: 99,
MATNR: 13,
RATE: 0.11,
VALUE: 11,
OLD_VAL: 12,
}
]
// using a spread operator instead of concat
const result = arr.map(el => Object.fromEntries([
...inputArr.map(key => [key, el[key]]), ['OLD_VAL', el.OLD_VAL]
]));
console.log(result);

You can do this with either way :
Good old for loop
const newArr = [];
for(let obj of arr) {
let newObj = {}
for(let key of input) {
console.log(key)
newObj[key] = obj[key]
}
newArr.push(newObj);
}
Or using map and reduce methods of the Array interface:
arr.map( e => input.reduce((acc, key) => {
acc[key] = e[key];
return acc;
},{}))
PS: dont forget that object keys are strings so your input variable should be :
const input = ['VKORG', 'VTWEG', 'MATNR']

Related

Filter an array by equal id

I got an array like this and I need to filter this array with the same user id with all the occurrences with the service_id corresponding to user_id:
Array [
Object {
"service_id": 14,
"user_id": 56,
},
Object {
"service_id": 19,
"user_id": 59,
},
Object {
"service_id": 18,
"user_id": 56,
},
Object {
"service_id": 18,
"user_id": 56,
},
]
And I need to filter the array like this:
Array [
Object {
"user_id": 56,
[
{"service_id":14},
{"service_id": 18}
]
},
Object {
"user_id": 59,
[
{"service_id": 19},
]
},
]
var array = [{"service_id": 14,"user_id": 56,},{"service_id": 19,"user_id": 59,},
{"service_id": 18,"user_id": 56,},{"service_id": 18,"user_id": 56}]
const groupByUserId = (array, key) => {
return array.reduce((result, currentValue) => {(
//Create a new array as key if there is not found
result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
return result;
}, {}); // empty object after initialization
};
const grouped = groupByUserId(array, 'user_id');
console.log(grouped)
In Javascript your array should look like this:
var array = [{"service_id": 14,"user_id": 56},{"service_id": 19,"user_id": 59},
{"service_id": 18,"user_id": 56},{"service_id": 18,"user_id": 56}]
There is an assumption to be made here to identify user_id as key in the new grouped array in order to populate the user's similar service_id inside its corresponding array.
const groupByUserId = (array, key) => {
return array.reduce((result, currentValue) => {(
//Create a new array as key if there is not found
result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
return result;
}, {}); // empty object after initialization
};
const grouped = groupByUserId(array, 'user_id');
console.log(grouped)
Your output array must be as the below example I suppose.
You can use Array.reduce for that.
const data = [
{
"service_id": 14,
"user_id": 56,
},
{
"service_id": 19,
"user_id": 59,
},
{
"service_id": 18,
"user_id": 56,
},
{
"service_id": 18,
"user_id": 56,
},
]
const output = data.reduce((acc, curr) => {
const node = acc.find((item) => item.user_id === curr.user_id);
if (node) {
node.list.push({service_id: curr.service_id})
} else {
acc.push({
user_id: curr.user_id,
list: [{service_id: curr.service_id}]
})
}
return acc;
}, []);
console.log(output)

Given array of parameters, make array from array of objects

I have this array:
course_ids: [11, 70, 3]
And this array of objects:
arr: [{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}]
Given these two, I want to make an array of course_hour_ids: [56, 72, 12]
How can I do that using React.js?
At first filter then map
let objArray = [
{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},
{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
];
let course_ids = [11, 70, 3];
let result = objArray.filter(array => course_ids.some(filter => filter == array.course_id)).map(a => a.course_hour_id);
console.log(result);
You colud filter initial array and then map the result array on course_hour_id like:
let arr = [
{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
},{
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
]
let course_ids = [11, 70, 3];
let res = arr.filter(el => {
return course_ids.includes(el.course_id);
})
console.log(res.map(el => el.course_hour_id))
const course_ids = [11, 70, 3];
const arr = [{
course_id: 11,
course_hour_id: 56,
name: 'John',
},
{
course_id: 70,
course_hour_id: 72,
name: 'Lily',
}, {
course_id: 3,
course_hour_id: 12,
name: 'Mike',
}
];
const result = arr.map(x => {
if (course_ids.includes(x.course_id))
return x.course_hour_id
});
console.log(result)
No need to use .filter
course_ids
.map(course_id =>
arr.find(arrItem =>
arrItem.course_id === course_id)
?.course_hour_id);
The above solutions uses optional chaining. If you don't use that you can write:
course_ids
.map(course_id =>
arr.some(arrItem =>
arrItem.course_id === course_id)
? arr.find(arrItem =>
arrItem.course_id === course_id).course_hour_id
: null
);

Create new array of objects based on two arrays in Javascript

I want to get the array of objects created from two simple arrays:
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
The expected result:
const result = [
{ id: 20, value: false },
{ id: 2, value: false },
{ id: 35, value: true },
{ id: 86, value: true },
];
The array1 length is the one that matters. So I need to find matched values in both arrays as showed in the expected result.
Thank you very much for your help.
You can combine map with includes:
array1.map(i => ({id: i, value: array2.includes(i)}))
Should be simple. Loop through the first array using Array.map & return an object.
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
const result = array1.map(i => ({ id: i, value: array2.includes(i) }))
console.log(result)
Create a set from the second array:
const a2set = new Set(array2);
then map your first array:
array1.map(v1 => ({id:v1, value: a2set.has(v1)}))
Start a loop against first array and check if that element exists in second array or not.
If element exists push it to array containing objects with flag true or else as false.
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
var objArray = []
array1.forEach(function(elem){
objArray.push({
id : elem,
value : array2.indexOf(elem) != -1 ? true : false
});
});
console.log(objArray);
You can use array indexOf to find if the item is inside the second array.
const array1 = [20, 2, 35, 86];
const array2 = [8, 86, 15, 23, 35, 44];
let output = [];
array1.forEach((number) => {
output.push({
id: number,
value: array2.indexOf(number) !== -1
});
});
console.log(output);
Try a simple for loop:
const array1 = [20, 2, 35, 86];
const array2 = [8, 86, 15, 23, 35, 44];
var res = [];
for (var i = 0; i < array1.length; i++) {
if (array2.includes(array1[i])) {
res.push({ id: array1[i], value: true });
} else {
res.push({ id: array1[i], value: false });
}
}
console.log(res);
Try the following. If performance is important, or if the arrays might include a large amount of elements, I'd consider using sets for better lookup performance.
const array1 = [20, 2, 35, 86]
const array2 = [8, 86, 15, 23, 35, 44]
const result = array1.map(element => {
return {
id: element,
value: array2.includes(element)
};
})

Find the same elements of an array from other arrays?

I have a movie, I want to show films of the same genres, what am I doing wrong?
My film (find):
{
"id": 1,
"title": "Kill Bill",
"genre_ids": [1, 10, 15]
}
// All films (movies)
{
"id": 2,
"title": "Leon",
"genre_ids": [1, 12, 15]
},
{
"id": 3,
"title": "Spider-man",
"genre_ids": [12, 32, 15]
},
{
"id": 3,
"title": "Marvel cap",
"genre_ids": [20, 38, 1]
},
// My code
return find.map(i => { // My film
return i.genre_ids.map(ids => {
return movies.data.results.filter(movie => { // All films
return movie.genre_ids.filter(idMov => idMov === ids)
})
})
});
Your movie (find) is an object, not an array, it doesn't have a map function to call.
A Solution:
Create a function that can from a single genre and array of movies return an array of matching movies by genre
const matchByGenre = movies => genre =>
movies.filter(movie => movie.genre_ids.includes(genre));
Iterate over the film's genre_ids array for matches. This yields an array of array matches, flatten them with .flat to a single array. The set is used to remove duplicates and have the result returned back to you as array.
const movieSet = Array.from(
new Set(film.genre_ids.map(matchByGenre(movies)).flat())
);
const film = {
id: 1,
title: "Kill Bill",
genre_ids: [1, 10, 15]
};
const movies = [
{
id: 2,
title: "Leon",
genre_ids: [1, 12, 15]
},
{
id: 3,
title: "Spider-man",
genre_ids: [12, 32, 15]
},
{
id: 4,
title: "Marvel cap",
genre_ids: [20, 38, 1]
},
{
id: 5,
title: "The Big Lebowski",
genre_ids: [20, 38, 2]
}
];
const matchByGenre = movies => genre =>
movies.filter(movie => movie.genre_ids.includes(genre));
const movieSet = Array.from(
new Set(film.genre_ids.map(matchByGenre(movies)).flat())
);
console.log(movieSet);
Note: If the syntax for matchByGenre is confusing, it is a curried function taking a movies array and returns a callback function to be used by array::map

How to loop values in an array with similar values but distinctively?

var items =[
{ID:1,day:'mon',val1:10,val2:20,val3:10},
{ID:2,day:'mon',val1:11,val2:70,val3:55},
{ID:3,day:'mon',val1:15,val2:27,val3:37},
{ID:4,day:'teu',val1:9,val2:17,val3:11}
]
var workDays = ['mon','teu']
I need to loop through the item array above.. and append the data elsewhere in the following form:
--loop block starts--
Day:// from workDays
Values:// from item array
--loop block ends---
Final result Should be something like
Day:'mon'
Values:10,20,10...(display all values corresponding to 'mon' in item array
How do i go about that?
You can use ES6 destructuring and easily achieve what you want:
var items = [{
ID: 1,
day: 'mon',
val1: 10,
val2: 20,
val3: 10
},
{
ID: 2,
day: 'mon',
val1: 11,
val2: 70,
val3: 55
}, {
ID: 3,
day: 'mon',
val1: 15,
val2: 27,
val3: 37
}, {
ID: 4,
day: 'teu',
val1: 9,
val2: 17,
val3: 11
}
]
var workDays = ['mon', 'teu']
const result = workDays.map(day => {
const dayItems = items.filter(item => item.day === day);
const values = dayItems.reduce((a, {
val1,
val2,
val3
}) => [...a, val1, val2, val3], []);
return {
Day: day,
Values: values,
};
});
console.log(result);
You could achieve it using map, filter and flat. something like this
const items = [
{"ID": 1, "day": "mon", "val1": 10, "val2": 20, "val3": 10},
{"ID": 2, "day": "mon", "val1": 11, "val2": 70, "val3": 55},
{"ID": 3, "day": "mon", "val1": 15, "val2": 27, "val3": 37},
{"ID": 4, "day": "teu", "val1": 9, "val2": 17, "val3": 11}
];
const workDays = ["mon", "teu"];
const result = workDays.map(day => {
return {
"Day": day,
"values": items.filter(item => item.day === day).map(i => {
return [i.val1, i.val2, i.val3];
}).flat()
};
});
console.log(result);

Categories

Resources