Filter arrays inside array [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an array that contains arrays and objects, and I want a function to filter only the arrays inside the initial array, example:
const myArray = [
[1,2,4],
{name:'john'},
[2,4,5],
{name: 'jack'}
]
And then get a variable that only contains [1,2,4] and [2,4,5]
Thanks!

You can use filter to return values based on a condition. Below uses the .isArray method of Array class to determine if a value is an array.
const arrays = myArray.filter(Array.isArray)
Example:
const myArray = [
[1,2,4],
{name:'john'},
[2,4,5],
{name: 'jack'}
]
const arrays = myArray.filter(Array.isArray)
console.log(arrays)

Try using:
const myArray = [
[1,2,4],
{name:'john'},
[2,4,5],
{name: 'jack'}
]
let arr= myArray.filter((elem)=>{
return Array.isArray(elem);
})

Array.prototype.filter returns a new array. It executes a callback for every item in the array. The first argument of the first callback is the first item, the first argument of the second callback is the second item etc. If the callback returns a truthy value, the item that was the first argument of that callback is added to the new array.
Array.isArray(arg) returns a boolean based on if the argument is an Array.
const myArray = [
[1,2,4],
{name:'john'},
[2,4,5],
{name: 'jack'}
]
function untitled(array) {
return array.filter((item) => Array.isArray(item));
}
answer = untitled(myArray);
console.log(answer);

myArray.filter(v=>Array.isArray(v))

Related

Add all the elements in an array without using loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How to add elements without using loops and the built-in method of the array like for , foreach etc) and built in methods(like reduce,map...) of array
How can we do the addition?
var arr =[1,2,2,3,4...];
arr length also dynamic.
You can use Spread ... operator like this
var arr1 = [1, 2, 3, 4];
var arr2 = [5,6,7,8];
console.log([...arr1, ...arr2]);
Addition as in sum?
const arr = [1,2,2,3,4];
// normal way
let sum = arr.reduce((a,b) => a+b)
console.log(sum)
// weird way not using loops but still using a built-in method
sum = eval(arr.toString().replace(/,/g,"+"))
console.log(sum)
You can use concat for that whice creates a new array and returns the result so arr1 and arr2 will remain unchanged.
const arr1 = [1, 2];
const arr2 = [3, 4,5,6,7,8];
const combined = arr1.concat(arr2);
console.log(combined);
console.log(arr1);
console.log(arr2);
If you want to mutate the original array you can use push and the spread operator (...):
const a = [1,2]
const b = [3,4,5,6]
a.push(...b)
console.log(a);

what is the best way to push an array of objects into an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Here is the array of objects that is to be push to an array
[{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
How to achieve this array below from the above
"array": [
[
[
11,
21
],
[
31,
41
],
[
10,
20
]
]
]
Use Array.prototype.map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
Map it
let arr = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
let result = [arr.map(({a,b}) => [a,b])];
console.log(result);
Use reduce to form an array and then Object.values to extract the object prop values for each sub array.
const arr = [{
a: 11,
"b": 21
}, {
"a": 31,
"b": 41
}, {
"a": 10,
"b": 20
}];
const result = arr.reduce((acc, x) => {
const values = Object.values(x);
acc.push(values);
return acc;
}, [])
console.log({
array: result
});
[].concat(array.map((val)=>Object.values(val)))
If all you want to do is push each element of B into A you can do A.concat(B).
If you want to make a new array with all the values your can
c = ([]).concat(A,B)
For your array of objects with values, you could
c = []; for ( vals in b ) c.concat(Object.values(vals);

Delete repeated and concatenate values Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have this Arrays
const array1 = ['546546546546', '01/01/2020', 'A'];
const array2 = ['866465465465', '01/01/2020', 'B'];
const array3 = ['546546546546', '05/01/2020', 'B'];
The first value from array1 and Array3 is the same. But the rest is not the same.
I want to eliminate those that are repeated in the value 0 and concatenate what they have in 1 and 2.
To get something like this:
['546546546546', '01/01/2020 A - 05/01/2020 B'];
['866465465465', '01/01/2020 B'];
You can create a dictionary with the first element in the array as a key. I used Array.prototype.reduce to create a dictionary and finally extract the values out of the dictionary with Object.values will give your result
const array1 = ['546546546546', '01/01/2020', 'A'];
const array2 = ['866465465465', '01/01/2020', 'B'];
const array3 = ['546546546546', '05/01/2020', 'B'];
// group it into a single array for looping
const input = [array1, array2, array3];
const groupedValues = input.reduce((group, [key, date, name]) => {
// if exist concat the date and name with previous value
if (group[key]) {
group[key][1] = `${group[key][1]} - ${date} ${name}`;
} else {
// initialize if doesnt exist
group[key] = [key, `${date} ${name}`];
}
return group;
}, {});
const output = Object.values(groupedValues);
console.log(output);

How to Count Unique Arrays in a Multidimensional Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am looking for a way to not only find unique arrays within a multidimensional array, but also count how many times a particular array occurs.
For Example
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
// Code
???
// Results
uniqueArrays === [[1,2], [1,3], [1,4]]
theCount ==== [2, 1, 3]
Edit:
I didn't realize that I had to show my attempts of how I should solve a problem before I asked a question.
I do know how to count the length of an array use the length() method. I do know how to filter unique arrays from a multi-dimensional array. I did not post my attempts using those tools though because those two issues have been solved to death.
You can map each inner array to a stringified version of itself using .map(JSON.stringified). Now, using this new array, you can reduce it to an object which contains each stringified array as a key, and keeps the number of occurrences as its value. While reducing, you can check whether or not the object's key has already been set using a[k] = (a[k] || 0)+1. If it has already been set, it will use the current number stored at the key and increment it by 1, if it hasn't already been set it will set it equal to zero, and then increment it by 1 (which acts as the default value for any new keys (i.e newly seen arrays)).
Lastly, you can get the keys from your object which represent each unique array as strings using Object.keys(), and parse each back into a non-stringified array using JSON.parse. You can get the counts from your array by using Object.values() as this will get all the values (ie: the counters) of your reduced object and put them into an array.
See example below:
const arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
const arr_str = arr.map(JSON.stringify);
const arr_map = arr_str.reduce((a, k) => (a[k] = (a[k] || 0) + 1, a), {});
const uniqueArrays = Array.from(Object.keys(arr_map), JSON.parse);
const theCount = Object.values(arr_map);
console.log(uniqueArrays);
console.log(theCount);
you can use below code
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
var test = [], obj ={};
arr.forEach(val => {
if(test.indexOf(val.toString()) == -1){
test.push(val.toString());
obj[val.toString()] = 1;
uniqueArrays.push(val);
}else{
obj[val.toString()] += 1;
}
})
theCount = Object.values(obj);
console.log(uniqueArrays);
console.log(theCount);
Hope it will help you.

Sort index of array based on value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I get the wrong index value when i am adding more than 10 values in my observable array, when i am trying to get current object like observableArray.indexOf(this). So i created new variable index value and generated like below example. But on enter i want to sort my observable array in descending order. So I want to do something like below example.
I have list of object with value like below
1,20
2,40
3,10
4,50
And I want result like
3,20
2,40
4,10
1,50
I want to sort my index value based on descending order of number in knockout observable.
Sort an mapped array based on value.
Find the index of value based on the index from sorted array.
var obj = [{
index: 1,
value: 20
}, {
index: 2,
value: 40
}, {
index: 3,
value: 10
}, {
index: 4,
value: 50
}];
var sortedArr = obj.map(function(el) {
return el.value;
}).sort(function(a, b) {
return b - a
});
var mapped = obj.map(function(el) {
var index = sortedArr.indexOf(el.value) + 1;
el.index = index;
return el;
});
console.log(JSON.stringify(mapped,null,4));

Categories

Resources