I’m trying to map a nested array and return the words that have more letters than 6, I have been stuck for a while with this problem so I’d like to get some help
const array = [["hellow",'pastas'],["travel", "militarie"],["oranges","mint"]]
const arrayOne = array.map(new => new).filter(arr =>arr.length > 6)
You can flat array first and than filter out words with length greater than 6
const array = [['hellow','pastas'],['travel', 'militaries'],['oranges','mint']]
const arrayOne = array.flat(1).filter(e=> e.length > 6 )
console.log(arrayOne)
You can use the code below. This code uses .map() and .filter() to check if the length is greater than 6, and adds it to the array if it is.
const array = [["hellow","pastas"],["travel", "militarie"],["oranges","mint"]];
const arrayOne = array.map(e1 => e1.filter(e2 => e2.length > 6)).flat();
console.log(arrayOne);
I think better will be the filter() method instead.
array.filter(function (c) {
return c.length < 6;
});
But first use the flat() method.
There are many ways to do it.
You can use flatMap and filter:
const array = [['hellow','pastas'],['travel', 'militarie'],['oranges','mint']];
const result = array.flatMap(x => x.filter(y => y.length > 6));
console.log(result);
Another way is to use reduce and filter:
const array = [['hellow','pastas'],['travel', 'militarie'],['oranges','mint']];
const result = array.reduce((acc, x) => [...acc, ...x.filter(y => y.length > 6)], []);
console.log(result);
Related
i have an array like this:
arrays = [
{"y":"2020","OVO":3},
{"y":"2021","OVO":2,"Dana":1},
{"y":"2019","OVO":2,"Dana":1,"Shopepay":3},
{"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1}, //length = 5
{"y":"2022","OVO":2,"Dana":1,"Shopepay":1}
];
now i want to create new array based on longest object key from arrays.
should from this:
{"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1}, //length = 5
to this :
['OVO','Dana','Shopepay','Gopay']
how to achieve that in javascript?
thanks in advance.
Looking for something like this?
const arrays = [
{"y":"2020","OVO":3},
{"y":"2021","OVO":2,"Dana":1},
{"y":"2019","OVO":2,"Dana":1,"Shopepay":3},
{"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1},
{"y":"2022","OVO":2,"Dana":1,"Shopepay":1}
];
const longestArray = arrays.sort((a, b) => Object.keys(a).length - Object.keys(b).length)?.pop(); // sort for most object with most properties
console.log(Object.keys(longestArray).slice(1)); // remove first element from array
Or as simple one-liner:
Object.keys(arrays.sort((a, b) => Object.keys(a).length - Object.keys(b).length)?.pop()).slice(1);
Use .reduce() to achieve your goal
arrays = [
{"y":"2020","OVO":3},
{"y":"2021","OVO":2,"Dana":1},
{"y":"2019","OVO":2,"Dana":1,"Shopepay":3},
{"y":"2018","OVO":2,"Dana":1,"Shopepay":4,"Gopay":1}, //length = 5
{"y":"2022","OVO":2,"Dana":1,"Shopepay":1}
];
const max = arrays.reduce((prev, current) => (prev.length > Object.keys(current).length) ? prev : Object.keys(current)).splice(1)
console.log(max)
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);
I have an array of array, how to find if a value exists inside this array in javascript. Here is the code example
let multival = [['Individual'], ['Non-Individual'],null]
Now I have to find if string 'Non-Individual' is present in this array of array or not, can anyone have solution in this regards
You could use Array.prototype.some() to check the string is present in the array of array.
const multival = [['Individual'], ['Non-Individual'], null];
const searchItem = 'Non-Individual';
const ret = multival.some(
(x) => Array.isArray(x) && x.some((y) => y === searchItem)
);
console.log(ret);
Out of interest, a recursive solution for arrays with any level of nested depth (And I believe quicker than a solution using flat() due to short circuiting):
function nestedIncludes(arr, val) {
let check = i => Array.isArray(i) ? i.some(check) : i === val;
return arr.some(check);
}
let myArr = [[[['foo'],1],2],3,5];
let test = nestedIncludes(myArr, 'foo');
console.log(test); // true
Try flat and includes function:
const multival = [['Individual'], ['Non-Individual'],null]
const exists = multival.flat().includes('Non-Individual');
console.log(exists ? 'exists' : 'non-exists')
Note: I didn't notice, but User863 comment with the same answer.
Method 1, Using findIndex, optional chaining and includes
Method 2, Using some, optional chaining and includes
// Method 1, Using `findIndex` and `includes`
const find = (arr, item) => arr.findIndex((arr2) => arr2?.includes(item)) > -1;
// Method 2, Using `some` and `includes`
const find2 = (arr, item) => arr.some((arr2) => arr2?.includes(item));
let multival = [["Individual"], ["Non-Individual"], null];
console.log(find(multival, "Individual"));
console.log(find2(multival, "Individual"));
console.log(find(multival, ""));
console.log(find2(multival, ""));
I have multidimensional array, that shown from console.log(temp) in my dashboard.component.ts just like this:
[[],[],[],[],[],[],[],[],[],[],[{"user_id":"ismail.rahman.saanin#gmal.com","status":"Idle"},{"user_id":"lutfi.aldi.nugroho#gmil.com","status":"Overload"}]]
Basically, this kind of array (contain null array inside) is rare condition. But it disturb me, i cant parse the data.
My Dashboard.component.ts
this.scheduleService.getShiftSchedule().subscribe((temp)=>{
this.api = temp;
//console.log(temp);
var ids = [['user_id', 1], ['status', 2]],
result = Object.keys(temp).map(o => ids.map(([key, id]) => ({ id, content: temp[o][key] })));
this.tablePresetData = result;
})
My question is, how to filter data if there is condition null array in multidimensional array like in my case ?
Need Help, Thanks guys...
You can use .filter() and return element .length where 0 evaluates to false
let [res] = array.filter(({length}) => length)
or use .flat()
let res = array.flat()
You can check if length is greater than 0.
let arr = [[],[],[],[],[],[],[],[],[],[],[{"user_id":"ismail.rahman.saanin#gmal.com","status":"Idle"},{"user_id":"lutfi.aldi.nugroho#gmil.com","status":"Overload"}]];
arr = arr.filter(item => Array.isArray(item) && item.length > 0)
console.log(arr);
I want to sort the imgUrl array by click count. I have two arrays.
clickCount = [5,2,4,3,1]
imgUrl = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg']
In numpy it is easy. I use order = np.argsort(clickCount) then I create another array newArray = [imgUrl[i] for i in order].
How do I achieve the same effect in javascript (preferably vanilla)?
You can use a Schwartzian transform also known as Decorate-Sort-Undecorate (DSU) in python.
DSU:
Decorate - Use Array#Map to enrich each item in the array with the needed sort data
Sort - sort using the added data
Undecorate - extract the sorted data using Array#map again
Demo:
const dsu = (arr1, arr2) => arr1
.map((item, index) => [arr2[index], item]) // add the args to sort by
.sort(([arg1], [arg2]) => arg2 - arg1) // sort by the args
.map(([, item]) => item); // extract the sorted items
const clickCount = [5,2,4,3,1];
const imgUrl = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];
const result = dsu(imgUrl, clickCount);
console.log(result);
thanks to dankal444 for the refactor to the function
For completeness, here's my solution to the actual answer (providing argsort function), by expanding on Ori's answer with DSU.
Since sort is by default taking the first element, so implementing it as DSU is merely adding an index, sorting it, then taking the indices.
let decor = (v, i) => [v, i]; // set index to value
let undecor = a => a[1]; // leave only index
let argsort = arr => arr.map(decor).sort().map(undecor);
clickCount = [5, 2, 4, 3, 1]
imgUrl = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg']
order = argsort(clickCount);
newArray = order.map(i => imgUrl[i])
console.log(newArray);
Functional approach (like #Ori Drori's code) is always a charm to watch, but in this case, you only need to re-arrange an array's items. I believe that there is a simpler way to go and is a much easier code to read.
const clickCount = [5,2,4,3,1];
const imgUrl = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];
sortByArrayRefOrder = (data, orderRefArr) => {
let orderedArr = [], i=0;
orderRefArr.map( o => { orderedArr[o-1] = data[i++]});
return orderedArr.reverse();
}
console.log ( sortByArrayRefOrder(imgUrl, clickCount) );