Comparing array (start with option) by giving another array in JavaScript - javascript

I have two arrays;selectedFunction say array1. with these values
['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001']
and allFunctions say array2. with these values ;
[ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]
if element in array1 starts with the given element from array2, then push that element of array1 into myFinalSelectedFunctions[] say array3. In above arrays, 2nd and 3rd elements of array1 should be pushed into array3. How to perform such task in javascript/Nodejs ? I have basic knowledge of javascript, not an expert.

You can use .filter() with .some() to return true if a hex code from array1 .startsWith() a hex code in array2:
const array1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const array2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ];
const res = array1.filter(hex => array2.some(code => hex.startsWith(code)));
console.log(res);

Yo can do following:
const arr1 = ['0x0000000000000000', '0x4046ebae00000ab003','0xd6d75f5100000cd0001'];
const arr2 = [ '0x000fba16', '0x4046ebae', '0x517cf73e', '0xd6d75f51' ]
const arr3 = [];
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < arr2.length; j++) {
if (arr1[i].startsWith(arr2[j])) {
arr3.push(arr1[i])
}
}
}
console.log(arr3)
Answer by #nick-parsons is much cleaner. You can go for it.

Related

Looping through two arrays to fill a two dimensionnal array

I work on Angular and use Typescript. I have two arrays array1 and array2 which I have parsed from an API.
A console.log on array1 looks like this :
A console.log on array2 looks like this :
I'd like to create an two dimensionnal array which would merge the two arrays one element by element (id 0 with id 0, id 1 with id 1, id 2 with id 2 and so on). To be clearer the result would be :
[["Outils sali", "saunier"], ["outils elem", "outils trad"], ["outils trad", "outils sali"], .... ];
Would you have any ideas to realize that trick ?
Any help would be very appreciated, thank you !
If both have the same length just use a map operator
array1 = []; // imagine filled
array2 = []; // imagine filled
let result = array1.map((array1Value, index) => [array1Value, array2[index]]);
You can use Array.map() to give you the desired result, returning an element from arr1 and arr2 for each iteration.
const arr1 = ['outils sali', 'outils elem', 'outils trad', 'matériel', 'produit'];
const arr2 = ['saunier','outils trad', 'outils sali', 'outils trad', 'matériel'];
const result = arr1.map((el, idx) => [el, arr2[idx]]);
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const arr1 = ["outils sali", "outils elem", "outils trad", "materiel", "produit"];
const arr2 = ["saunier", "outils trad", "outils sali", "outils trad", "materiel"];
const newArray = []
let subArray = []
for(let i = 0; i<arr1.length; i++) {
subArray = createArray(arr1[i],arr2[i])
newArray.push(subArray)
}
function createArray(elem1,elem2) {
return [elem1,elem2]
}
console.log(newArray)

Filter if array include an element of another array

I have two arrays like:
arr1 = ["orange","banana"]
arr2 = [{"fruit"= ["pineapple","banana"]},{"fruit"= ["grapes","apple"]},{"fruit"= ["apple","orange"]}]
And i need to filter if in second array exists an item of the first.
I am trying to do this:
let kFilter = arr1.map(itemY => { return itemY; });
let filteredK = arr2.filter(itemX => kFilter.includes(itemX.fruit));
But no success :-(
First to avoid too much iteration convert the simple array to an object something like following. Otherwise the complexity will be high
const fruitMap = {
"orange": 1,
"banana": 1
};
Then you have to iterate over each of the items in second array
arr2.forEach(fruitsObj => {
let arr = fruitsObj['fruit'];
for (let i = 0; i < arr.length(); i ++) {
if (fruitMap[arr[i]]) {
arr.splice(i, 1);
}
}
})
//declaration variables correctly
let arr1 = ["orange","banana"]
let arr2 = [{"fruit" : ["pineapple","banana"]},{"fruit" : ["grapes","apple"]},{"fruit": ["apple","orange"]}];
//filter using reduce
arr2.filter((e)=>arr1.reduce((a,i)=>a||e["fruit"].includes(i),false))
//filter using some
arr2.filter((e)=>arr1.some((i)=>e["fruit"].includes(i)))

Update value of object with values in different array

I have two array with below structure:
Array1:
[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
Array2:
[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
result
Array1 =[{id:1234,name:"macaron",quantity:"330gm",rate:"300"},{id:5678,name:"Gelato",quantity:"450gm",rate:"500"}]
I want to be able to update the only rates of objects in Array1 with rate of objects in Array2.
If order or lengths of the arrays are different one efficient way is
create a Map of the new rates from Array2 then loop over Array1 ant get() from the Map.
This way you only iterate Array2 once instead of using multiple iterations of methods like find()
let Array1=[{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}],
Array2=[{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}];
const rateMap = new Map(Array2.map(({id, rate})=> [id, rate]));
Array1.forEach(e=> rateMap.has(e.id) && (e.rate = rateMap.get(e.id )))
console.log(Array1)
let Array1 = [
{id:1234,name:"macaron",quantity:"330gm",rate:"100"},
{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}
];
let Array2 = [
{id:1234,name:"macaron",quantity:"600gm",rate:"300"},
{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}
];
for (i = 0; i < Array1.length ; i++) {
Array1[i].rate = Array2[i].rate
}
console.log(Array1)
Array1 = Array1.map(item => {
return { ...item, rate: Array2.filter(rec => rec.id === item.id)[0].rate };
});
});
The cleanest solution I came up with.
But as charlietfl said: I make assumtion that both lengths are the same and in same order
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
console.log(this[i].rate)
this[i].rate = array2[i].rate;
console.log(this[i].rate)
}
}
array1.updateRate(array2);
console.log(array1)
Here is second (full) solution, where that asumption isn't made:
let array1 = [{id:1234,name:"macaron",quantity:"330gm",rate:"100"},{id:5678,name:"Gelato",quantity:"450gm",rate:"200"}]
let array2 = [{id:1234,name:"macaron",quantity:"600gm",rate:"300"},{id:5678,name:"Gelato",quantity:"800gm",rate:"500"}]
array1.updateRate = function(array2) {
for(let i = 0; i < this.length;i++) {
for(let j = 0; j < array2.lenght;j++) {
if(this[i].id === array2[j].id) {
this[i].rate = array2[j].rate;
break;
}
}
}
}
array1.updateRate(array2);
console.log(array2)

What is the best optimize way to check if array of arrays contains another array in JavaScript?

I am trying to find an optimized way to check if an array of arrays contains another array.
Example:
const result = [['a','b','c'],['d']];
const sample = ['d'];
Here, result contains an array that matches sample array. How to optimize a two for loop solution with a length check?
for(let i = 0 ; i <result.length; i ++){
let arr = result[i];
if(arr.length === sample.length){
for(let j = 0 ; j <sample.length; j ++){
if(arr[j] !== sample[j]){
return false;
}
}
return true;
}
}
Looking for a faster way.
You could simply do,
const result = [
['a', 'b', 'c'],
['d']
];
const sample = ['d'];
const sample2 = ['a', 'b'];
console.log(result.some(r => JSON.stringify(r) == JSON.stringify(sample)))
console.log(result.some(r => JSON.stringify(r) == JSON.stringify(sample2)))

Unsplit two arrays Javascript

I have the following code
var Louis = [ 'Louis.IX', 'Louis.VIII' ]
var array1 = [];
var array2 = [];
for (var i = 0; i < Louis.length; i++) {
var split = Louis[i].split(".");
array1.push(split[0]); // before the dot
array2.push(split[1]); // after the dot
}
console.log("Louisname", array1);
console.log("Louisnum", array2);
and the output is
Louisname [ 'Louis', 'Louis' ]
Louisnum [ 'IX', 'VIII' ]
Now any idea on how can i revert the output into the initial array? Please help me, thanks.
You can use .map() with its second index argument to join elements in the first array with the second array by returning a string which contains elements in both arrays like so:
const array1 = ["Louis", "Louis"];
const array2 = ["IX","VIII"];
const original = array1.map((v, i) => `${v}.${array2[i]}`);
console.log(original);
If you're new to JS, here is a more straightforward/imperative way of achieving the same result (see code comments for details):
const array1 = ["Louis", "Louis"];
const array2 = ["IX","VIII"];
const original = [];
for(let i = 0; i < array1.length; i++) { // loop through all elements in array 1
const original_str = array1[i] + "." + array2[i]; // join array element `i` in array1 with array element `i` in array2
original.push(original_str); // add the joined string to the `original` array
}
console.log(original);

Categories