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)
};
})
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have array of objects where I want to filter and combine results based on specific id. This is example:
[
{
id: 1,
items: [
{
id: 10,
values: [11],
},
{
id: 20,
values: [13, 14, 15],
},
],
},
{
id: 2,
items: [
{
id: 10,
values: [12],
},
{
id: 20,
values: [13, 15],
},
],
},
];
And this is expected result:
[
{
id: 10,
values: [11, 12],
},
{
id: 20,
values: [13, 14, 15],
},
];
I also need to filter duplicates. Thanks
Note: What if I want this result?
[
{
// here I want value for id 10 (it will be always one number)
value: 11,
// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13, 14, 15],
},
{
// here I want value for id 10 (it will be always one number)
value: 12,
// here I want values for id 20 (array of numbers) => remove possible duplicates
values: [13, 15],
},
];
I tried the same approach with Map, but without success. Basically I want to combine values based on ids.
You could do with Array.flatMap to filter all items in single array.
Then recreate the array with Array.reduce and push the value based on id into new value object
And use Array.filter ignore the duplicate values on array
Object.values return only the value of object in array format
Older
const arr = [ { id: 1, items: [ { id: 10, values: [11], }, { id: 20, values: [13, 14, 15], }, ], }, { id: 2, items: [ { id: 10, values: [12], }, { id: 20, values: [13, 15], }, ], }, ];
const res = Object.values(arr.flatMap(({items})=> items)
.reduce((acc,{id,values})=>{
acc[id] = acc[id] ?? {id,values:[]};
//check the object exist or not
let newArr = acc[id]['values'].concat(values);
let valArr = newArr.filter((v,i)=>newArr.indexOf(v) === i)
//remove the duplicates
acc[id]['values'] = valArr
return acc
},{}))
console.log(res)
Updated
const arr = [ { id: 1, items: [ { id: 10, values: [11], }, { id: 20, values: [13, 14, 15], }, ], }, { id: 2, items: [ { id: 10, values: [12], }, { id: 20, values: [13, 15], }, ], }, ];
function filterMethod(arr,value,values){
return arr.map(({items})=> ({
value:detector(items,value)[0],
values:detector(items,values)
}))
}
function detector(items,idVal){
let ind = items.findIndex(({id})=> id === idVal);
return ind > -1 ? items[ind]['values'] : ['']
}
console.log(filterMethod(arr,10,20))
let array1 = [{id: 1, name:'xyz', inclusions: [43,23,12]},{id: 2, name: 'abc',inclusions:[43, 12, 90]},{id: 3, name:'pqr', inclusions: [91]}];
let array 2 = [43, 12, 90, 45];
Now i want to get all the elements of array1, which has inclusions present in array2.
So output would be something:
result = [{id: 1, name:'xyz', inclusions: [43,23,12]},{id: 2, name: 'abc',inclusions:[43, 12, 90]}
I am using two for loops, which i don't want. How can i achieve it using filter and includes.
Filter by whether .some of the items of the object being iterated over are included:
let array1 = [{id: 1, name:'xyz', inclusions: [43,23,12]},{id: 2, name: 'abc',inclusions:[43, 12, 90]},{id: 3, name:'pqr', inclusions: [91]}];
let array2 = [43, 12, 90, 45];
const filtered = array1.filter(({ inclusions }) => inclusions.some(
num => array2.includes(num)
));
console.log(filtered);
I have two arrays:
1- inventory that contains some elements
2- indices_dates that contains the indices of the elements I want from inventory.
Is there a simple way to create an array formed by the elements of inventory if their index is contained into indices_dates
Example:
let inventory
let indices_dates
let final = []
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
---Some Code To Get Final Array---
The output I would like:
final = [25, 40, 20, 17]
I did the following:
let inventory
let indices_dates
let final = []
let i
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
for (i in indices_dates) {
final.push(inventory[indices_dates[i]])
}
But I am wondering if there is another, more direct way to achieve it.
You can use Array.map() to iterate the indices array, and take the values from inventory:
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5]
const final = indices_dates.map(idx => inventory[idx])
console.log(final)
You can do as #Ori suggest or alternative solution is :
Another approach is using forEach :
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5];
let final = [];
indices_dates.forEach(data => final.push(inventory[data]))
console.log(final)
Using for of :
const inventory = [25, 35, 40, 20, 15, 17]
const indices_dates = [0, 2, 3, 5];
let final = [];
for (let dateIndex of indices_dates){
final.push(inventory[dateIndex])
}
console.log(final)
I have a JavaScript object like this
server1:[38,1,2,7]
server2:[6,2,1,4
server3:[160,30,21,20]
I want to insert the elements of this objects in an array like this
data1=[
[
{name:"Success", y:38},
{name:"Failure", y:1},
{name:"Aborted", y:2},
{name:"Unstable", y:7}
],
[
{name:"Success", y:6},
{name:"Failure", y:2},
{name:"Aborted", y:1},
{name:"Unstable", y:4}
],
[
{name:"Success", y:160},
{name:"Failure", y:30},
{name:"Aborted", y:21},
{name:"Unstable", y:20}
]
]
The first element of the key of JavaScript object is success, second element is failure, third element is unstable and fourth element is aborted.Is there any way I can do this? Any help will be appreciated
You can use Object.values method to get object values and use
Array#map
method to generate the array.
const data = {
server1: [38, 1, 2, 7],
server2: [6, 2, 1, 4],
server3: [160, 30, 21, 20]
}
let res = Object.values(data).map(([s, f, a, u]) => [{
name: "Success",
y: s
},
{
name: "Failure",
y: f
},
{
name: "Aborted",
y: a
},
{
name: "Unstable",
y: u
}
])
console.log(res);
You could take an array for the names and map the outer and inner values.
var server1 = [38, 1, 2, 7],
server2 = [6, 2, 1, 4],
server3 = [160, 30, 21, 20],
names = ["Success", "Failure", "Aborted", "Unstable"],
result = [server1, server2, server3]
.map(s => names.map((name, i) => ({ name, y: s[i] })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you prefer good ol' loops over functional map() approach, use this:
var test = {
server1: [38, 1, 2, 7],
server2: [6, 2, 1, 4],
server3: [160, 30, 21, 20]
};
function makeArray(input) {
var array = [];
for (var server in input) {
array.push([
{name: "Success", y : input[server][0]},
{name: "Failure", y : input[server][1]},
{name: "Aborted", y : input[server][2]},
{name: "Unstable", y : input[server][3]},
]);
}
return array;
}
console.log(makeArray(test));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an array [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20].
Whenever the element of the array is equal to 20 I would like to wrap it with an asterisk on either side like this [1, 5, *20*, 17, 6, 12, 13, *20*, 1 , 14, *20*].
How can I achieve this?
You can use map
let arr = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20]
let result = arr.map(o => o === 20 ? '*20*' : o);
console.log(result);
Doc: map()
You can use Arrays forEach to modify the elements of the array. elem is each element and i is the respective index. We are using forEach to modify the existing array. Since this is what you desired..
let arr = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20]
arr.forEach((elem, i) => {
if (elem === 20) {
arr[i] = "*20*"
}
})
console.log(arr)
function rollDice(max, times, bonus) {
var rolls = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20];
rolls.forEach((elem, i) => { if (elem === 20) { rolls[i] = "twenty" } });
for (var i = 0; times > i; i++)
{
max = Math.floor(max);
rolls.push(Math.floor(Math.random() * max) + 1 | + parseInt(bonus));
}
console.log(rolls);
}
rollDice(20, 5);
The problem you are experiencing is that you need to convert the integer number into strings. JavaScript has several ways to cleverly do this behind-the-scenes, but if you are still gaining an understanding of that, it's better to be explicit about what data types you start with (integers), and what data types you expect to end with (strings).
You transform the array, "mapping" over each item, transforming it to a string, and then if the string matches "20", you add the asterisks.
const start_array = [1, 5, 20, 17, 6, 12, 13, 20, 1, 14, 20];
const new_array = start_array.map((integer) => {
let number_string = integer.toString();
if (number_string === "20") {
number_string = "*" + number_string + "*";
}
return number_string;
})
console.log(new_array);