How to get the matching second array of object in es6 - javascript

I have two array of objects: - better solution
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
Expected output be:
if first array and second array id matches means take the second array name
in above example id 2 matches and we need id:2,name: panasonics.
o/p:
[{id:1,name:"samsung"},{id:2,name:"panasonics"},{id:3,name:"Lg"},{id:5,name:"samsung"},{id:7,name:"Apple"}]

Combine the arrays using Array.concat(), reduce them into a Map by id, and then convert the Map's values to an array with Array.from():
const unionBy = (field, ...arrays) => Array.from(
[].concat(...arrays)
.reduce((r, o) => r.set(o.id, o), new Map)
.values()
);
const array1 = [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
const result = unionBy('id', array1, array2);
console.log(result);

You can use a simple .forEach() loop like below (you can also use a for loop if you want, but .forEach() is easier).
This code loops through array1, and loops through array2 in that loop. It then checks if the ids are the same. If there are, the name is appended to result.
const array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
const array2 = [{id:5,name:"samsung"},{id:2,name:"panasonics"},{id:7,name:"Lg"}];
let result = [];
array1.forEach(e1 => {
array2.forEach(e2 => {
if (e1.id == e2.id) {
result.push(e2.name);
}
});
});
console.log(result);

Use map() and concat() like the following code
array1= [{id:1,name:"samsung"},{id:2,name:"nokia"},{id:3,name:"Lg"}];
array2 = [{id:5,name:"samsung"}, {id:2,name:"panasonics"},{id:7,name:"Lg"}];
var array3=array1.map(function(i,v){
if(array2[v].id==i.id){
return array2[v]
}
else return i
})
array4=array3.concat(array2);
console.log(array4);

Related

From an array, find the array that has the true values for the objects

Given array:
const array = [{1: true},{2: false},{3: true},{}.....];
Filter the given array by only including objects with values of true.
Looking for the shortest solution.
const onlyTrue = array.filter((el, ind) => el[ind + 1] === true);
This will work only if indexes in array objects are ordered and starting from 1, as it is in your example.
Assumptions (based on what's in your example):
Each object in the array only has at least 1 property in it
The first property on each object is the one we care about
The property in each object is different every time
const array = [{1: true},{2: false},{3: true}];
const results = array.filter(item => Object.values(item)[0]);
If you want to avoid any false positives from truth-y values (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy), then change the filter call to this instead:
const results = array.filter(item => Object.values(item)[0] === true);
const array = [{1: true},{2: false},{3: true}];
const array2 = [];
array.forEach(filterTrue);
function filterTrue(item){
for(x in item){
if(item[x]===true){
array2.push(item);
}
}
}
console.log(array2);
Hope this helps you.

Make an array A with the result of each value of array B splitted by pipe

I have an array of strings. Some of the strings within this array have a pipe character. I would like to split the strings by "|" and store all the unique values into a new array.
What would be an efficient way to get a temporary array with all the splited values in it, without using poor performance loops?
Once I have the temporary array with all the splited values in it, I plan de remove all duplicates like this :
var result = [...new Set(result)]
var arr = ["A|B|C","B|A","E|A|D","F"]
// result does not have to be sorted
var expectedResult = ["A","B","C","D","E","F"]
Use flatMap() and split() to get a single array, and use a Set to retain unique elements:
const array = ["A|B|C","B|A","E|A|D","F"];
const result = [...new Set(array.flatMap(v => v.split('|')))];
console.log(result);
.join('|') array as a string with pipes between all letters, then .split('|') by the pipe and then remove dupes with Set()
let data = ["A|B|C", "B|A", "E|A|D", "F"];
console.log([...new Set(data.join('|').split('|'))]);
I would go with
const result = arr.map(item => item.split("|")).flat();
const deduped = [...new Set(result)]
One more option:
const inputArray = ["A|B|C","B|A","E|A|D","F"];
const result = inputArray.reduce((acc, value) => acc.push(...value.split('|')) && acc, []);
console.log(result);
const splitSet = (arr) => {
const set = new Set();
for(const item of arr) {
const splited = item.split("|");
for(const piece of splited) {
set.add(piece);
}
}
return Array.from(set);
}
splitSet(arr); //result
The first thing that comes to my mind is this
const arr = ["A|B|C","B|A","E|A|D","F"];
const flatArr = arr.join('|').split('|');
const expectedResult = [...new Set(flatArr)];

Javascript: How to get values of an array at certain index positions

I have an array of values
arr = ["a","b","c","d"]
and I have another array of indexes
indexes = [0,2]
What is the best way to get the values of the array at these indexes ?
If I apply the method to the values above
it should return
["a","c"]
Use Array.map:
arr = ["a","b","c","d"]
indexes = [0,2]
const res = indexes.map(e => arr[e])
console.log(res)

How to return indices from javascript filter function (filtered based on values)?

I want to do something that seems simple but I cannot figure it out.
I want to use the javascript function 'filter' to find values in an array greater than a value and then return the indices that correspond the those filtered values (or values in that indice range from another array.
arr1 = [1,3,7,9,11];
arr1 = [2,4,8,10,12];
arr1.filter(x => x > 7);
// returns: [9,11]
// desired return: [4,5] (indices from arr1 where values from arr1 that were filtered) and/or [10,12]
// (values from arr2 where values from arr1 that were filtered)
I know the code is not right but I cannot figure out how to get desired result.
Any help would be appreciated. Thanks
You can use map in combination with filter to achieve this:
arr1.map((x, i) => [x,i]).filter(([x,i]) => x > 7).map(([x,i]) => i);
This maps the array to an array of pairs where the first element is the original number and the second is the original index. Then it filters the pairs by the first element of each pair before mapping it back to the indexes.
You can Array#reduce and do this in one run of the array by checking and transforming the data at once
const arr1 = [1,3,7,9,11];
const result = arr1.reduce((acc, x, index) => acc.concat(x > 7 ? index : []), []);
console.log(result);
You can do it like this:
var arr1 = [2,4,8,10,12];
console.log(arr1.filter(x => x>7).map(m => arr1.indexOf(m)))
returns [2, 3, 4]
The most efficient method would be to use reduce. Here I'm using array spread syntax to optionally add the index to the array used as the initial value of the accumulator.
var arr1 = [1,3,7,9,11];
var indexes = arr1.reduce((acc, cur, idx) => acc = cur > 7 ? [...acc, idx] : acc, []);
console.log(indexes);
Just add another map call and indexOf
PS: If there are duplicate values, indexOf return only first occurrence.
Alternatively, if you are not particular about filter, you can use reduce which can done with one iteration.
const arr1 = [1,3,7,9,11];
const arr2 = [2,4,8,10,12];
const filter = arr => arr.filter(x => x > 7).map(x => arr.indexOf(x));
console.log(filter(arr1))
console.log(filter(arr2))
const filter2 = arr => arr.reduce((acc, x, i) => (x > 7 && acc.push(i), acc), []);
console.log(filter2(arr1))
console.log(filter2(arr2))

other method to loop in array ? javascript

can y'all explain other methods to loop in the array ??
function blabla(number){
for ( let i = 0 ; i < number.length ; i++)
..........
}
console.log([1,2,3,4,5,6])// true
console.log([2,4,6,8]) // true
console.log([1,2,6,8,9,11, 25]) false
can we use forEach to loop? how about map and filter?
There's a ton of different ways to iterate through an array.
Let's use this array as an example: const array = ['foo', 'bar']
for..of
This will iterate through the values in the array.
const array = ['foo', 'bar']
for (element of array) {
console.log(element)
}
for..in
This will iterate through the properties in the array. In this case, that would be the array indexes. I wouldn't recommend this to iterate arrays, to be honest.
const array = ['foo', 'bar']
for (element in array) {
console.log(element)
}
Array.forEach()
This will run a callback for each one of the elements in an array. This allows you to pass a function to it, which will take each element as the parameter.
const array = ['foo', 'bar']
const doSomething = e => console.log(e)
array.forEach(element => console.log(element))
//or
array.forEach(doSomething)
Array.map()
This will run a callback for each one of the elements in an array, just like in the forEach method, but in that function you can return a value modifying the original value of the element, and the return value of the map function will be the array with the modified values.
This will add 'test' to the end of each of the elements, and return the resulting array.
const array = ['foo', 'bar']
const mappedArray = array.map(element => element.concat('test'))
console.log(mappedArray)
Array.filter()
This will run a function for each one of the elements in an array, and depending whether you return a truthy or falsy, it will include or exclude that element from the returning array
This will filter out all elements that contain the letter "f".
const array = ['foo', 'bar']
const filteredArray = array.filter(element => !element.includes('f'))
console.log(filteredArray)
Those are just some of them. I'd also recommend looking into Array.reduce(), Array.every() and Array.some().
this will start counting from 0
function blabla(number){
$.each(new Array(number),
function(n){alert(n);}
);
}
blabla(3);

Categories