How to compare objects of two arrays in JavaScript - javascript

I had taken two arrays in JavaScript
arr1 = ["empid","Name"];
arr2 = [{"keyName":"empid" ,"keyValue":"2"}]
And I want to check the value of keyName should be any one element from arr1.

some short-circuits after finding the first match so it doesn't necessarily have to iterate over the whole array of objects. And it also returns a boolean which satisfies your use-case.
const query1 = ['empid','Name'];
const arr1 = [{'keyName':'empid' ,'keyValue':'2'}];
const query2 = ['empid','Name'];
const arr2 = [{'keyName':'empid2' ,'keyValue':'five'}];
const query3 = ['empid','Name', 'test'];
const arr3 = [{'keyName':'test2' ,'keyValue':'five'},{'keyName':'test' ,'keyValue':'five'}];
function found(arr, query) {
return arr.some(obj => {
return query.includes(obj.keyName);
});
}
console.log(found(arr1, query1));
console.log(found(arr2, query2));
console.log(found(arr3, query3));

Use _.isEqual(object, other);
It may help you.

Related

How to compare a part of an array item with a part of an array item from a second array?

If I have two arrays with files
arr1 = ['file1.webp', 'file2.webp', ...];
arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg', ...];
how would I check which array items are equal, minus the *.format part?
The idea is that, if there are two equal items, a webp and an alternative source are available. While if an item has no match, no webp source was provided. Both cases would lead to different image handling later on.
I could compare the items inside two arrays like so: let match = arr1.find( val => arr2.includes(val) );
But this compares each entire item. I only want to compare the file names. The formats in which the files were provided need to be cut off, so I get:
arr1 = ['file1', 'file2', ...];
arr2 = ['file1', 'file2', 'file3', 'file4', ...];
I can then filter out all matches between the two arrays. I've been searching for a solution for a real while, but I'm still not sure how to get there.
With a function that trims off the file extension, you can construct a Set of one of the transformed arrays. Then iterate over the other array and check whether its transformed item is in the Set or not:
const arr1 = ['file1.webp', 'file2.webp'];
const arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'];
const transform = str => str.replace(/\.[^.]+$/, '');
const set1 = new Set(arr1.map(transform));
for (const item of arr2) {
if (set1.has(transform(item))) {
console.log('Match for', item);
} else {
console.log('No match for', item);
}
}
You can use filter() with nested some(). To get the file name from complete name use split('.')and get the first element using .split('.')[0]
let arr1 = ['file1.webp', 'file2.webp'];
let arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'];
let res = arr2.filter(a => arr1.some(b => a.split('.')[0] === b.split('.')[0]));
console.log(res)
You could filter by looking to the right side.
const getName = s => s.replace(/\.[^.]+$/, '');
var array1 = ['file1.webp', 'file2.webp'],
array2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'],
set1 = new Set(array1.map(getName)),
common = array2.filter(s => set1.has(getName(s)));
console.log(common);
write extract method to get value to compare. Just use the extract method in your code. Alternatively, you can build an arr2Obj to not to repeat the searches.
const arr1 = ["file1.webp", "file2.webp"];
const arr2 = ["file1.jpg", "file2.png", "file3.jpg", "file4.jpg"];
const extract = item => item.split(".")[0];
let match = arr1.find(val => arr2.map(x => extract(x)).includes(extract(val)));
console.log(match);
// Alternatively,
const arr2Obj = Object.assign({}, ...arr2.map(x => ({ [extract(x)]: 1 })));
const match2 = arr1.find(val => extract(val) in arr2Obj);
console.log(match2);

How do I get multiple index on an Array

I am trying to get multiple index positions on an Array for a Boolean value.
I have tried applying a loop using while and for to iterate more then one index position with no success so far.
Here is my code:
let jo = [1,2,3,4,5]
let ji = [1,2,3]
let checker = (arr1,arr2) => {
let falsy = arr1.every(num => arr2.includes(num)) == false ?
arr1.map(falsy => arr2.includes(falsy)) : "tba";
//the block below is the frustrated attempt:
let i = falsy.indexOf(false);
while(i>=0){
return falsy.findIndex(ih => ih == false)
}
}
console.log(checker(jo,ji))
I would like to get the index where false occurs stored in a variable that has iterated over all array so I can use this variable to return just the false values on falsy like this:
return falsy[i] = [4,5]
Then after that I will add more to the first if statement to check both arr1 x arr2 or arr2 x arr1
Thanks in advance!
It looks like you're attempting to get the difference between two arrays. This is a fairly comment use-case for Sets. In this case, your code would look like this:
let jo = [1,2,3,4,5]
let ji = [1,2,3]
const checker = (arr1, arr2) => {
return new Set(arr1.filter(x => !new Set(arr2).has(x)))
}
console.log(checker(jo, ji)); // {4, 5}
If you wanted to get the indexes of the differences, you would need to apply a map to the result of the new Set like so:
const checker = (arr1, arr2) => {
const difference = new Set(arr1.filter(x => !new Set(arr2).has(x)));
return Array.from(difference).map(value => arr1.indexOf(v));
}

Alphabetically sort array with no duplicates

I'm trying to create a function that takes an array of strings and returns a single string consisting of the individual characters of all the argument strings, in alphabetic order, with no repeats.
var join = ["test"];
var splt = (("sxhdj").split(""))
var sort = splt.sort()
var jn = sort.join("")
join.push(jn)
function removeDuplicates(join) {
let newArr = {};
join.forEach(function(x) { //forEach will call a function once for
if (!newArr[x]) {
newArr[x] = true;
}
});
return Object.keys(newArr);
}
console.log(removeDuplicates(join));
I can not get the current code to work
Check out the comments for the explanation.
Links of interest:
MDN Array.prototype.sort.
MDN Set
var splt = ("sxhdjxxddff").split("")
// You need to use localeCompare to properly
// sort alphabetically in javascript, because
// the sort function actually sorts by UTF-16 codes
// which isn't necessarily always alphabetical
var sort = splt.sort((a, b)=>a.localeCompare(b))
// This is an easy way to remove duplicates
// by converting to set which can't have dupes
// then converting back to array
sort = [...new Set(sort)]
var jn = sort.join("");
console.log(jn);
Something like this :) Hope it helps!
const string = 'aabbccd';
const array = string.split('');
let sanitizedArray = [];
array.forEach(char => {
// Simple conditional to check if the sanitized array already
// contains the character, and pushes the character if the conditional
// returns false
!sanitizedArray.includes(char) && sanitizedArray.push(char)
})
let result = sanitizedArray.join('')
console.log(result);
Try this:
const data = ['ahmed', 'ghoul', 'javscript'];
const result = [...data.join('')]
.filter((ele, i, arr) => arr.lastIndexOf(ele) === i)
.sort()
.join('');
console.log(result)
There are probably better ways to do it, one way is to map it to an object, use the keys of the object for the used letters, and than sorting those keys.
const words = ['foo', 'bar', 'funky'];
const sorted =
Object.keys(
([...words.join('')]) // combine to an array of letters
.reduce((obj, v) => obj[v] = 1 && obj, {}) // loop over and build hash of used letters
).sort() //sort the keys
console.log(sorted.join(''))

ES6 Merge two arrays (array contains another array inside) based on key Typescript or Javascript

I want to merge two arrays both array contains another array inside. refer below two arrays.
const arr1=
[{"projectId":30278,"projectName":null,"details":[{"amount":"9097457.11","currency":"USD","paymentDate":"2016-05-16T00:00:00"}]},{"projectId":37602,"projectName":null,"details":[{"amount":"8234743.0","currency":"USD","paymentDate":"2019-04-30T00:00:00"},{"amount":"8234743.0","currency":"USD","paymentDate":"2019-04-23T00:00:00"}]}]
const arr2=
[{"projectId":30278,"projectName":null,"details":[{"amount":"8097457.11","currency":"USD","paymentDate":"2016-05-16T00:00:00"}]},{"projectId":37602,"projectName":null,"details":[{"amount":"7234743.0","currency":"USD","paymentDate":"2019-04-30T00:00:00"},{"amount":"7234743.0","currency":"USD","paymentDate":"2019-04-23T00:00:00"}]}]
when i used ES6 spread operator, both values are appended to single array. But I want to merge based upon prjectId in that array.
So after merge, i need to get the result like below
const result =
[{"projectId":30278,"projectName":null,"details":[{"amount":"9097457.11","currency":"USD","paymentDate":"2016-05-16T00:00:00"},
{"amount":"8097457.11","currency":"USD","paymentDate":"2016-05-16T00:00:00"}
]},
{"projectId":37602,"projectName":null,"details":[{"amount":"8234743.0","currency":"USD","paymentDate":"2019-04-30T00:00:00"},{"amount":"8234743.0","currency":"USD","paymentDate":"2019-04-23T00:00:00"},
{"amount":"7234743.0","currency":"USD","paymentDate":"2019-04-30T00:00:00"},{"amount":"7234743.0","currency":"USD","paymentDate":"2019-04-23T00:00:00"}
]}]
const arr1=
[{"projectId":30278,"projectName":null,"details":[{"amount":"9097457.11","currency":"USD","paymentDate":"2016-05-16T00:00:00"}]},{"projectId":37602,"projectName":null,"details":[{"amount":"8234743.0","currency":"USD","paymentDate":"2019-04-30T00:00:00"},{"amount":"8234743.0","currency":"USD","paymentDate":"2019-04-23T00:00:00"}]}]
const arr2=
[{"projectId":30278,"projectName":null,"details":[{"amount":"8097457.11","currency":"USD","paymentDate":"2016-05-16T00:00:00"}]},{"projectId":37602,"projectName":null,"details":[{"amount":"7234743.0","currency":"USD","paymentDate":"2019-04-30T00:00:00"},{"amount":"7234743.0","currency":"USD","paymentDate":"2019-04-23T00:00:00"}]}]
var fullArray = [...arr1,...arr2];
var mergedData ={};
fullArray.forEach(function(data){
if(mergedData[data.projectId]){
mergedData[data.projectId]["details"] = mergedData[data.projectId]["details"].concat(data.details)
} else {
mergedData[data.projectId] = data;
}
})
console.log(Object.values(mergedData))
You can easily achieve that using Lodash unionBy function.
const result = _.unionBy(arr1, arr2, 'projectId')
You can also try this in this case scenario.
let mergedArr = [];
let projectIdsArr1 = arr1.map(item => item.projectId);
arr2.map(outerLoopItem => {
if (projectIdsArr1.includes(outerLoopItem.projectId)) {
let found = arr1.find(innerLoopItem => innerLoopItem.projectId === outerLoopItem.projectId);
found.details = [...found.details, ...outerLoopItem.details];
mergedArr.push(found);
} else mergedArr.push(outerLoopItem);
});
console.log(mergedArr);

Reactjs trying to merge arrays

Let's say I have two array's
let array1 = ["H","E","", "","O","","","R","L","D"];
let array2 = ["","","L","L","","W","O","","",""];
I want to merge them such that they would then contain:
array3 = ["H","E","L", "L","O","W","O","R","L","D"];
How would I achieve this?
To be more clear I have a target array which is array3 an empty array and then I'm generating random characters and if they match array3 adding them to the blank array in the specific position with react state. It is just not storing the position and character each time but just changing it. SO my idea is to set the state such that I merge the current state with the new characters that are found.
TLDR:- Brute forcing Hello World meme.
You can use Array.prototype.map() to create a new array array3 out of iterating over array1 and get the l (letters) and if any l evaluates to falsey then get the letter at the same i (index) in the array2.
Note that instead of declaring your arrays with let you should always use const because it makes code easier to read within its scope, and const variable always refers to the same object.
Code example:
const array1 = ["H","E","", "","O","","","R","L","D"];
const array2 = ["","","L","L","","W","O","","",""];
const array3 = array1.map((l, i) => l || array2[i]);
console.log(array3);
Try it:
let arr1 = ["H","E","", "","O","","","R","L","D"];
let arr2 = ["","","L","L","","W","O","","",""];
let arr3 = [];
arr1.forEach((val, index) => {
if (val === '') {
arr3[index] = arr2[index];
} else {
arr3[index] = val;
}
});
console.log(arr3);

Categories

Resources