Related
I have an array with lists:
[ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]
The output im expecting is:
[ [ 1, 2 ], [ 3, 5 ] ]
Im not able to iterate and find duplicates when we have lists in an array.
You can compare two arrays using JSON.stringify. First, call the reduce method on the original array starting with an empty arr as the accumulator, then push each item of the original array inside the acc array only if it hasn’t already been pushed inside acc. In order to check if acc doesn’t already contain that item(array), you can use a method like some and see if any array inside the acc array, is equal to the current array or not.To compare the arrays use JSON.stringify.
const data = [ [ 1, 2 ], [ 3, 5 ], [ 2, 5 ], [ 3, 5 ], [ 1, 2 ] ]
const includesArray = (arr1, arr2) =>
arr1.some(item=>
JSON.stringify(item)==JSON.stringify(arr2));
const result=data.reduce((acc,item)=>
!includesArray(acc,item)?
[...acc,item]:
acc,[]);
console.log(result);
I made the logic, maybe inefficient but it works.
Here's the code:
const sameCombi = (arr) => {
let result = []
arr.forEach((ele) => {
let same = arr.filter((val) => val.join() === ele.join())
if (result.find((valRes) => valRes.join() === ele.join())) return false
if (same.length > 1) result.push(ele)
})
return result
}
console.log(
sameCombi([
[1, 2],
[3, 5],
[2, 5],
[3, 5],
[1, 2]
])
)
I've searched high and low for this, but can't find examples similar enough to my own. I have virtually no js experience, so I appreciate any help!
Here is my code snippet:
const arr = [];
for (let i = 1; i <= 3; i++) {
arr.push({
name: ["name1","name2","name3"],
data: [0+i,1+i,2+i],
})
}
This is obviously a very simplified version of my use case, but it should be fine for getting an answer.
For all three [arr]'s that are created, I need to increase each value within arr.data by 1. I have no idea how to do this, or if it's even possible.
Edited for sample outputs:
In it's current form, the output will be:
Array [
Object {
name: "name1",
data: Array [1, 2, 3]
},
Object {
name: "name2",
data: Array [2, 3, 4]
},
Object {
name: "name3",
data: Array [3, 4, 5]
}
]
I need the arr.data arrays to add 1 (or any other value) to each item in each data sub-array, so the output would be:
Array [
Object {
name: "name1",
data: Array [2, 3, 4]
},
Object {
name: "name2",
data: Array [3, 4, 5]
},
Object {
name: "name3",
data: Array [4, 5, 6]
}
]
I hope that helps. I'm sure I'm using the wrong terminology for this.
Thanks
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 10 arrays of data that look like this:
var arr = [1,2,3,4,5,6,7,8,9,10]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9']
...8 More Arrays
Each array will have exactly the same number of elements every time. I wanted to know the best way to generate an array of objects that look like this that combines the various arrays:
overallarray = [{
arr1 = 1,
arr2 = 'hello'
...
},
{
arr1 = 2,
arr2 = 'hello1'
...
}]
I recognize that I can use a large number of for loops but am looking for a more optimized solution that someone might have.
This is where Array.map() will be your friend. You can iterate through any of the arrays (since they have the same number of elements) and then access each element by index to get the corresponding value for each array in your dataset, like so:
var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
let mapped = arr.map((elem, index) => {
return {
arr1: arr[index],
arr2: arr2[index],
arr3: arr3[index]
}
});
console.log(mapped);
Edit: If you wanted to access them generically, you can add all of your arrays to one dictionary and iterate over the key/value pairs, like so:
var arr = [0,1,2,3,4,5,6,7,8,9]
var arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'];
var arr3=['foo','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9'];
// combine all arrays into single dataset
let data = {arr, arr2, arr3};
let mapped = arr.map((elem, index) => {
// iterate over the key/value pairs of the dataset, use the key to generate the
// result object key, use the value to grab the item at the current index of the
// corresponding array
return Object.entries(data).reduce((res, [key, value]) => {
res[key] = value[index];
return res;
}, {});
});
console.log(mapped);
Assuming arr1,arr2 are not desired names of resulting object properties, if you need something
that scales nicely for arbitrary number of data arrays
assigns arbitrary key names (not necessarily corresponding to array variable names, or, worse, property name(s) that can't be valid variable name are needed)
works muuuch faster than accepted solution ;)
You may do the following:
const arr1 = [1,2,3,4,5,6,7,8,9,10],
arr2=['hello','hello1','hello2','hello3','hello4','hello5','hello6','hello7','hello8','hello9'],
keyNames = ['id', 'greeting'],
group = (...arrays) => (keys) =>
arrays.reduce((res, arr, idx) =>
(arr.forEach((e,i) => res[i][keys[idx]] = e), res),
Array.from({length:arrays[0].length}, () => ({}))
)
console.log(group(arr1,arr2)(keyNames))
.as-console-wrapper {min-height:100%;}
Just iterate all arrays with 1 loop counter:
var dataArrayOne = [1, 2, 3, 4 ];
var dataArrayTwo = ["hello", "hello1", "hello2", "hello3" ];
...
var resultArray = [];
for (var i = 0; i < 4; i++)
{
var combined = {
arr1: dataArrayOne[I],
arr2: dataArrayTwo[i]
...
};
resultArray.push(combined);
}
You can get from this:
[ [1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]
]
to this:
[ [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
]
with this function:
const combine =
(...arrs) =>
[ arrs.map(xs => xs[0])
, ... ( arrs.every(xs => xs.length === 1)
? []
: combine(...arrs.map(xs => xs.slice(1)))
)
];
combine
( [1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]
);
Then from this:
[ [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
]
to this:
[ {arr1: 1, arr2: 4, arr3: 7}
, {arr1: 2, arr2: 5, arr3: 8}
, {arr1: 3, arr2: 6, arr3: 9}
]
with this function:
const to_obj =
(...arrs) =>
arrs.map(arr =>
Object.fromEntries(
arr.map((x, i) => [`arr${i+1}`, x])));
to_obj
( [1, 4, 7]
, [2, 5, 8]
, [3, 6, 9]
)
Hopefully connecting the two functions together is straightforward.
A note about performance
With exactly 10 arrays of 10 elements each, it is unlikely that you can tell whether a particular solution performs better than another. You should probably go for the solution that feels right in terms of readability or maintenance.
By these criteria you should probably exclude mine; just wanted to share a different approach.
As the question indicates, I need to compare the values of an array of this type [1,2,3], with the values of a key of an array of objects [{id: 1, name: 'jhon'}, {id: 2 , name: 'max'}] in this case I want to compare it with the value of the id key, I write the following example of what I need:
if I have this array of objects:
[
{
id: 1
name: 'jhon'
},
{
id: 2,
name: 'max'
},
{
id: 3,
name: 'fer'
}
]
and I have this array:
[1,2,3,4,5]
I need to compare them and obtain the values that are not present in the array of objects, in the previous example the values 4 and 5 are not present in the array of objects, so I need to obtain a new array or the same, but with the values that do not they were, [4,5]
NOTE: this should also work if I have an array, only with numbers that are not present, for example [8,9], they should return those same values.
EDIT: it is possible to obtain in a new array those values that are only present in the array of objects. For example, with the arrays of the previous code:
[{id: 1, name: 'jhon'}, {id: 2, name: 'max'}, {id: 3, name: 'fer'}]
now this array would have the following values [1,4,5] with the previous answers I get the following array [4,5] what is correct. how can I get the values [2,3] in a new array.
You can use filter and find
let arr1 = [{id: 1,name: 'jhon'},{id: 2,name: 'max'},{id: 3,name: 'fer'}]
let arr2 = [1, 2, 3, 4, 5];
let result = arr2.filter(o => !arr1.find(x => x.id === o));
console.log(result);
Update: This is basically the reverse of the first example. You filter the arr2 and check if the id exists on arr1. Then, use map to return the id
let arr1 = [{id: 1,name: 'jhon'},{id: 2,name: 'max'},{id: 3,name: 'fer'}]
let arr2 = [1,4,5];
let result = arr1.filter(o => !arr2.find(x => x === o.id)).map(o=>o.id);
console.log(result);
Doc: filter(), find()
Create a Set from the ids of arr1 using Array.map(). Then filter arr2 by checking if the Set has the number:
const arr1 = [{"id":1,"name":"jhon"},{"id":2,"name":"max"},{"id":3,"name":"fer"}];
const arr2 = [1,2,3,4,5];
const arr3 = [1, 5];
const difference = (arr1, arr2, key) => {
const arr1Values = new Set(key ? arr1.map(({ [key]: v }) => v) : arr1);
return arr2.filter((n) => !arr1Values.has(n));
};
// array of primitives and array of objects
console.log(difference(arr1, arr2, 'id'));
// two arrays of primitives
console.log(difference(arr3, arr2));
You can use filter to check if id property of element in arr2 matches to the current element in arr2
const arr1 = [{"id":1,"name":"jhon"},{"id":2,"name":"max"},{"id":3,"name":"fer"}];
const arr2 = [8,9];
var diffArray = arr2.filter(x => !arr1.filter(y => y.id === x).length);
console.log(diffArray);
Answer
[ 8,9 ]
You can use .filter() and .includes():
let arr1 = [{id: 1,name: 'jhon'},{id: 2, name: 'max'},{id: 3,name: 'fer'}],
arr2 = [1, 2, 3, 4, 5];
let result = (
ids => arr2.filter(n => !ids.includes(n))
)(arr1.map(({id}) => id));
console.log(result);
Description:
Create a new array by extracting only ids from first array using .map().
Filter elements using .filter() and .includes() to filter only those elements of second array that doesn't exists in newly created array.
Docs:
Array.prototype.map()
Array.prototype.filter()
Array.prototype.includes()
Object Destructuring
Arrow Functions
You could take a set with the given ids and then delete the ones of the object. Later return the array with the leftover ids.
var data = [{ id: 1, name: 'jhon' }, { id: 2, name: 'max' }, { id: 3, name: 'fer' }],
ids = [1, 2, 3, 4, 5],
result = Array.from(data.reduce((s, { id }) => (s.delete(id), s), new Set(ids)));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }