How do I get multiple index on an Array - javascript

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));
}

Related

Do anyone understand this reduce method problem Im having?

Do anyone understand why console.log(posArr) is printing [1,2,3] and not [0,1,2]. Im trying to push to nOfPos all the index positions of my array :)
function combinations(x) {
let arr = x.toString().split('');
console.log(arr)
let nOfPos = [];
let posArr = arr.map(x => nOfPos.push(arr.indexOf(arr[x])));
let mult = posArr.reduce((acum, item) => acum * item);
console.log(posArr);
console.log(mult);
}
combinations(123)
The problem is due to two errors in your code. Firstly push() returns the new length of the array, so that's why the mapped output contains the incremental 1,2,3....
Secondly, you need to search for x within arr, so you only need to pass x to indexOf().
With those issues corrected the code works:
function combinations(x) {
let arr = x.toString().split('');
let posArr = arr.map(x => arr.indexOf(x));
let mult = posArr.reduce((acum, item) => acum * item);
console.log(posArr);
console.log(mult);
}
combinations(123)
That being said, the purpose of posArr is a little redundant; it will always be an array of incremental values, up to the length of the string -1.
In addition, mult is redundant too as it will always be 0, as you are multiplying by 0.
You could use a 'for in' loop to get the array indexes.
let posArr = [];
for (ix in arr) {
posArr.push(ix)
}

How to compare objects of two arrays in 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.

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);

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);

Split is not doing anything when used inside filter

I tried using this function to filter an array based on index and return the splitted string into new array
const arr = ['arr 1','arr 2','arr 3','arr 4']
const newArr = arr.filter((val,index)=> {
if(index <= 1) {
return val.split(' ')
}
})
newArr should return this,
[['arr','1'],['arr','2']]
But it return this,
["arr 1", "arr 2"]
Here is the code in JS BIN: https://jsbin.com/zoguwoyexe/edit?js,console
Split works inside map function, but I wonder why it doesn't work inside filter, anyone knows about this?
filter expects you to return true-y or false-y values. It keeps trues and discards falses. It does not return the values you return, it returns a subset of the input array.
By using filter and map, like this, should get what you expect.
const arr = ['arr 1','arr 2','arr 3','arr 4']
const newArr = arr
.filter((val,index) => (index <= 1))
.map((val, index) => val.split(' '));

Categories

Resources