Reactjs trying to merge arrays - javascript

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

Related

I am looking for an efficient way to remove items from a JavaScript array if they are present in another array. Using indexOf

I want to remove those items from arr_2 which contains the domain name from arr_1
let arr_1 = ["domain1.com", "domain2.com"];
let arr_2 = [
"domain1.com/about-us",
"domain3.com/contact-us",
"domain4.com/privacy-policy",
"domain2.com/pricing-plans",
"sub.domain2.com/home-1",
];
let filtered_arr = [];
arr_2.forEach((item) => {
if (item.indexOf(arr_1) == -1) {
filtered_arr.push(item);
}
});
console.log(filtered_arr);
i want the result ["domain3.com/contact-us", "domain4.com/privacy-policy"] from this code, but it prints the whole arr_2
You can't call indexOf on a string and pass an array as an argument.
You should use find to check if item has a domain from arr_1.
And it's a lot cleaner code using filter than forEach.
let arr_1 = ["domain1.com", "domain2.com"];
let arr_2 = [
"domain1.com/about-us",
"domain3.com/contact-us",
"domain4.com/privacy-policy",
"domain2.com/pricing-plans",
"sub.domain2.com/home-1",
];
let filtered_arr = arr_2.filter(item => {
return !arr_1.find(domain => item.includes(domain));
});
console.log(filtered_arr);
Note: This would also filter out "example.com/domain1.com".
Your code right now is returning the whole arr_2 because your filtering logic does not check if each item of arr_2 contains one of the matching strings in arr_1.
indexOf(arr_1) is essentially searching each item in arr_2 for the entire arr_1 array. The function will always return -1 because each item of arr_2 is a string and will never match with the entire arr_1 array.
I assume you'd want to go through each item in arr_1 as well, so you should probably do arr_1.forEach((item1) => { }) inside the forEach loop for arr_2, and do the indexOf check inside this inner loop.
you can achive it using filter some and includes
let arr_1 = ["domain1.com", "domain2.com"];
let arr_2 = [
"domain1.com/about-us",
"domain3.com/contact-us",
"domain4.com/privacy-policy",
"domain2.com/pricing-plans",
"sub.domain2.com/home-1",
];
const arr3 = arr_2.filter(url => !arr_1.some(domain => url.includes(domain)))
console.log(arr3)

Merging two Array one after another Javascript [equal length]

I need to merge two array into one,one after another is there any better way?
for example ,
const arr1 = [1,2,3,4,5];
const arr2 = [a,b,c,d,e];
const resultIWant = [1,a,2,b,3,c,4,d,5,e]
Short and clear if both arrays are same length:
const arr1 = [1,2,3,4,5]
const arr2 = ['a','b','c','d','e']
const res = arr1.flatMap((e, idx) => [e, arr2[idx]])
console.log(res)
This can be done fairly easily using the reduce method. Here is my example below, I iterate through arr1 using reduce() and as I push the current value (c) to the accumulator (a), I also push the value from arr2 of the same index.
In my code below, this looks like a.push(c, arr2[i]) but you could also achieve this using a.push(arr1[i], arr2[i]), using arr1[i] instead of c if you want to keep both push values looking consistent.
const arr1 = [1,2,3,4,5];
const arr2 = ['a','b','c','d','e'];
const result = arr1.reduce((a,c,i) => (a.push(c, arr2[i]), a), []);
console.log(result);

How to Enter multiple items in an array to another array at a specific index?

I have an array
array1 = [1,2,3,6,7,8]
array2 = [40,50]
How can i push items in array2 to array1 to get a result
result = [1,2,3,40,50,6,7,8];
keep in mind its not a simple concatination, need to insert the scecond array in specific index.
array1.splice(3, 0, array1 ); => splice doesnt accept another array.
How can i enter items in diffrent array to a specific index?
Im trying this in angular
array1 .splice(3, 0,...array2);
and getting the im getting spread array doesn't support in tslib
var array1 = [1,2,3,6,7,8]
var array2 = [40,50]
function cobmine(arr1,arr2,index){
var arr3=arr1.splice(0,index);
var arr4=arr1.splice(-index);
return arr3.concat(arr2).concat(arr4)
}
var result=cobmine(array1,array2,3);
console.log(result);
Assuming your env does not support spread syntax for some reason you could stick to ES5 apply technique.
array1 = [1,2,3,6,7,8]
array2 = [40,50]
array1.splice.apply(array1, [3, 0].concat(array2))
console.log(JSON.stringify(array1))
You can use below code to add array at a specific index
const arr1 = [1,2,3,6,7,8]
const arr2 = [40,50]
const index = 3
const newArr = [
...arr1.slice(0, index),
...arr2,
...arr1.slice(index + 1),
]
// [1,2,3,40,50,6,7,8]

count words unique in array JavaScript

I have a Array, with a series of words that it collects in another function. What I intend is to count and separate those words that are unique and in the event that it is repeated do not count them. I've come this far, but the code stays in the first for. The goal is to count unique words in the array.
let arrayTemp = [];
Array1.forEach((item) => {
if(arrayTemp[0]){
arrayTemp[0] = item.perfilRoot;
}
for(let i = 0; i < arrayTemp.length; i++){
if(item.perfilRoot != arrayTemp[i]){
arrayTemp.push(item.perfilRoot);
}else{
break;
}
}
});
Convert to Set and check size
unique = new Set(YourArray);
console.log(unique.size)
You can try using Set which is an object that lets you store unique values.
const valuesYouWant = Array1.map(item => item.perfilRoot); // new array with values you want from Array1
const uniqueValues = [...new Set(valuesYouWant)]; // new array with unique values from array valuesYouWant
console.log(uniqueValues); // this will log your unique values
console.log(uniqueValues.length); // this will log the length of the new created array holding the unique values
You can consider using a Set.
array = [1,1,2,3,4,4,5];
unique = [...new Set(array)];
console.log (unique.length);
you can use Sets:
let arr = [1, 2, 3, 2, 3, 1]
console.log(new Set(arr).size)
or you can use object like maps to count uniques keys:
let arr = ['dog', 'dog', 'cat', 'squirrel', 'hawk', 'what a good dog'];
let m = {};
// count uniques words in array
arr.forEach(word => m[word] = 1);
// prints uniques counters
console.log('count:', Object.keys(m).length)
Since you only want to count the unique words, Set will not work. The code below looks at the array and only if the word is only found once in Array1 does it add it to arrayTemp
let arrayTemp = [];
Array1.map(a=>a.perfilRoot).forEach((item, index) => {
if (index +1 < Array1.length && Array1.slice(index +1).indexOf(item) === -1) arrayTemp.push(item);
});
console.log(arrayTemp);
console.log('number of unique words', arrayTemp.length);

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

Categories

Resources