Related
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.
I have two 2D arrays with identical elements but in a different order. I want to filter one taking into account if it already exists in the second array.
Examples of both arrays:
const firstArray = [['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['43452341','2020-4-28']] // there are like 40 arrays inside, not sorted
const secondArray = [['34347896', '2020´4-30'],['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['45892916','2020-4-28']] // there are like 300 arrays inside, not sorted
I want to eliminate the arrays of the "secondArray" that have the first index repeated in the "firstArray".
secondArray =[['34347896', '2020´4-30'], ['45892916','2020-4-28']]
I tried several things, I know that the most useful action is to use .reduce but it seems that I cannot make it work.
const notPosted = secondArray.reduce((a, b) => {
if (!firstArray[a[0]]) a.different.push(b);
return a;
}, {different: []});
Thanks!
I dont know which one is faster:
const arr1 = [['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['43452341','2020-4-28']]
const arr2 = [['34347896', '2020´4-30'],['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['45892916','2020-4-28']];
//First solution:
console.log("1) ",arr2.filter(e=>!arr1.some(e2=>JSON.stringify(e2)==JSON.stringify(e))))
//Second:
console.log("2) ",arr2.filter(e=>!arr1.some(e2=>e[0]==e2[0]&&e[1]==e2[1])))
You could convert your 2D array into an object with the zero index of each nested array being the key, and the first index being the value. (i.e. you already have your array in the perfect form for this [[key, val], [key, val], ...])
This is easy with Object.fromEntries(firstArray);
Then you call a simple filter function on your second array and return only those that have a key that is not in the object (lookups of keys in an object are fast - hash tables)
// there are like 40 arrays inside, not sorted
const firstArray = [['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['43452341','2020-4-28']]
// there are like 300 arrays inside, not sorted
const secondArray = [['34347896', '2020´4-30'],['45614726','2020-4-28'],['45610125','2020-4-28'],['45880944','2020-4-28'],['45892916','2020-4-28']];
const firstObj = Object.fromEntries(firstArray);
const secondFiltered = secondArray.filter(([key,val]) => !firstObj.hasOwnProperty(key));
console.log(secondFiltered);
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))
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);
I have two arrays. I want to filter one array which contains objects from another array.
let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];
After filtering these two arrays, I need filtered arrays as below.
let array= [4,0,6,0];
So, the filtered array contains the count for matched date and zero for unmatched values. But I'm getting only matched data.
Here is my code:
let array = _.map(_.filter(array1, function(o){
return _.includes(array2, o.date);
}), 'count');
Thank you
You can use map() and find() methods for this. You don't need filter() because for each element you will return count or 0 so you can just use map().
let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];
var array = array2.map(function(e) {
var f = array1.find(a => a.date == e);
return f ? f.count : 0
});
console.log(array)