Javascript nested array to integer - javascript

I have a nested array
const folder = [1, [2, [3, [4, [5, [6]]]]]];
please use the basic concept of javaScript.
I need return like 123456. what should I do?
i tried using for loops but it didn't work.

use the recursive function here.
find the below solution
const folder = [1, [2, [3, [4, [5, [6]]]]]];
let result = '';
function convert(arr) {
arr.forEach((val) => {
if (Array.isArray(val)) {
convert(val);
} else {
result = result + val
}
})
return result
}
console.log(convert(folder))

Related

Get values from array of arrays using push

I want to get values from an array of arrays, and I'm having difficulties doing it.
I have the following:
var id = 1; //value I want to use for the search
var _restrictions = [[1, 2], [2, 4], [5, 1], [1, 6]]; //arrays that I want to check
var arrVal = [];
By using the id, I want to retrieve all of the values, inside the arrays, where the id exits and store them in the array "arrVal".
For example:
_restrictions = [[1, 2], [2, 4], [5, 1], [1, 6]];
//arrVal will be: [2, 5, 6], because the id existing inside the arrays [1,2],
//[5,1] and [1,6]
The "_restrictions" array is a array of arrays that contain restrictions. They are independent values (the first one isn't the index or id).
How can I do that?
Thanks in advance!
Here's a version that will work for any size of nested array. It returns an flattened array of all values not including the id.
var id = 1;
var _restrictions = [[1, 2, 9], [2, 4], [5, 1], [1, 6]];
var arrVal = _restrictions.reduce((acc, c) => {
// Find the index of the id in each nested array
const i = c.findIndex(arr => arr === id);
// If it exists, splice it out and add it
// to the accumulator array
if (i > -1) {
c.splice(i, 1);
acc.push(...c);
}
return acc;
}, []);
console.log(arrVal);
EDIT: Updated code after the question is edited.
The question lacks a bit of clarity. I am assuming you want to filter the sub-arrays which have id in them i.e. contains the value 1.
let id = 1; //value I want to use for the search
let _restrictions = [[1, 2], [2, 4], [5, 1], [1, 6]];
let arrVal = _restrictions.filter((item) => {
return item.includes(id);
});
let new_array = arrVal.concat.apply([], arrVal).filter(x => x !== id);
console.log(new_array);
// [2, 5, 6]

Symmetric Difference of unknown number of arrays

Okay so I know there are multiple answers to this question but all of them use different approaches and I'm confused af rn.
The objective is to create a function that takes two or more arrays and returns an array of the symmetric difference of the provided arrays. The individual helper function is working fine but the code throws an error when I try to run it whole.
Here is my attempt:
function sym(args) {
let totalArguments = [...args];
var helper = function (arr1, arr2) {
return arr1.filter(item => arr2.indexOf(item) === -1).concat(arr2.filter(item => arr1.indexOf(item) === -1));
}
return totalArguments.reduce(helper);}
The input of sym([1, 2, 3],[2, 3, 4]) should be [1, 4]
Your code isn't working because you're only using the first argument:
function sym(args) {
let totalArguments = [...args];
This takes the first argument, args, and makes a shallow copy of the array - which doesn't accomplish anything because you aren't mutating anywhere anyway. If you wanted to accept a variable number of arguments, use argument rest syntax, to collect all arguments in an array:
function sym(...totalArguments) {
function sym(...totalArguments) {
var helper = function(arr1, arr2) {
return arr1.filter(item => arr2.indexOf(item) === -1).concat(arr2.filter(item => arr1.indexOf(item) === -1));
}
return totalArguments.reduce(helper);
}
console.log(sym([1, 2, 3], [2, 3, 4])) // [1, 4]
console.log(sym([1, 2, 3], [2, 3, 4], [0, 1])) // [0, 4], since 1 was duplicated
(There's no need to provide an initial value to the reducer)
Another option whose logic will probably be clearer to read and understand would be to iterate over all arrays and reduce into an object that keeps track of the number of times each number has occurred. Then, take the entries of the object, and return an array of the keys whose values are 1:
function sym(...args) {
const counts = args.reduce((a, arr) => {
arr.forEach((num) => {
a[num] = (a[num] || 0) + 1;
});
return a;
}, {});
return Object.entries(counts)
.filter(([, count]) => count === 1)
.map(([key]) => key);
}
console.log(sym([1, 2, 3], [2, 3, 4])) // [1, 4]
console.log(sym([1, 2, 3], [2, 3, 4], [0, 1])) // [0, 4], since 1 was duplicated

Array of Arrays to an Array of Unique Values Using Reduce/Map

I have an array of arrays, that needs to become 1 array of unique values.
[1, 3, 2], [5, 2, 1, 4], [2, 1]
I want to use reduce/map to solve the problem, but it doesn't seem to be working. I have solved the problem already with nested for loops like so:
function uniteUnique(arr) {
var args = Array.from(arguments);
var arr = [];
for (var i = 0; i < args.length; i++) {
for (var j = 0; j < args[i].length; j++) {
if (!arr.includes(args[i][j])) {
arr.push(args[i][j]);
}
}
}
return arr;
}
Now I tried to solve the problem here using reduce/map, but not getting the correct solution, like so:
function uniteUnique(arr) {
var args = Array.from(arguments);
return args.reduce(
(arr, a) => a.map(n => (!arr.includes(n) ? arr.push(n) : n)),
[]
);
}
console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));
I also tried to solve with reduce/map, using the older syntax, like so:
function uniteUnique(arr) {
var args = Array.from(arguments);
return args.reduce(function(arr, a) {
return a.map(function(n) {
if (!arr.includes(n)) {
return arr.push(n);
} else {
return n;
}
});
});
}
My guess is that I'm not doing something right with the return statements in the callback functions. Any help would be appreciated, thanks.
The problem is that:
arr.includes(n)
arr is an array of arrays, includes wont work there. You also never pass arr down the reduce chain.
The easiest to solve would be:
[...new Set(array.reduce((a, b) => a.concat(b), []))]
That just flattens the array, builds a Set for uniqueness and spreads it into an array. Or another elegant solution usong iterators:
function* flatten(arr) {
for(const el of arr) {
if(Array.isArray(el)) {
yield* flatten(el);
} else {
yield el;
}
}
}
const result = [];
for(const el of flatten(array))
if(!result.includes(el)) result.push(el);
Instead of using array#map use array#forEach and push unique number in the accumulator.
function uniteUnique(arr) {
var args = Array.from(arguments);
return args.reduce((arr, a) => {
a.forEach(n => (!arr.includes(n) ? arr.push(n) : n));
return arr
},[]);
}
console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));
Alternatively, you can array#concat all the array and then using Set get the unique value.
const arr = [[1, 3, 2], [5, 2, 1, 4], [2, 1]],
unique = [...new Set([].concat(...arr))];
console.log(unique);

Flatten an array with forEach

After checking out this post on flattening arrays, I noticed that no one had used the array method forEach. I gave it a try and failed, only receiving back an empty array:
let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];
arrays.forEach( (element) => {
result.concat(element)
})
console.log(result) //[]
Where did I go wrong?
You have to result = result.concat(element)
The concat() method is used to merge two or more arrays. This method
does not change the existing arrays, but instead returns a new array.
let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];
arrays.forEach((element) => {
result = result.concat(element)
})
console.log(result) //[]
Doc: concat
.concat() always returns a new array. It doesn't modify arrays on which it is operating.
You are supposing that .concat() will save result in its operand after completing its opeartion. However it is not the case. You need to save result explicitly after .concat():
result = result.concat(element);
Demo:
let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];
arrays.forEach((element) => {
result = result.concat(element)
});
console.log(result);
You can also use spread syntax instead of .forEach() to flatten array.
let result = [].concat(...arrays);
Demo:
let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [].concat(...arrays);
console.log(result);
concat returns a new array and hence you need to assign it to result like result = result.concat(element)
let arrays = [[1, 2, 3], [4, 5], [6]];
let result = [];
arrays.forEach( (element) => {
result = result.concat(element)
})
console.log(result)

difference between two arrays with javascript filter

Problem:
Compare two arrays and return a new array with any items not found in both of the original arrays. Use Array.filter and Array.indexOf to solve this.
function diff(arr1, arr2) {
var newArr = [];
//code here
return newArr;
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
I am not sure how to proceed. My solution is different from the above and uses a hard coded array. How do I make mine generic ?
function arrayNotContains(element){
var arr = [1, 2, 3, 5];
if(arr.indexOf(element) === -1){
return true;
}else{
return false;
}
}
var filtered = [1, 2, 3, 4, 5].filter(arrayNotContains);
console.log(filtered);
I got one more solution below. Is that ok ?
var arr1 = [1,2,3,5];
var arr2 = [1,2,3,4,5];
var filtered = arr2.filter(function(num) {
if (arr1.indexOf(num) === -1) return num;
});
You will want to use a closure:
function notContainedIn(arr) {
return function arrNotContains(element) {
return arr.indexOf(element) === -1;
};
}
var filtered = [1, 2, 3, 4, 5].filter(notContainedIn([1, 2, 3, 5]));
console.log(filtered); // [4]
Notice this is just a generalised version of your solution, I'm not saying that this is actually a valid solution for a symmetric diff function. For that, as it was stated in your problem, you'd need to do something like
function symmDiff(a, b) {
return a.filter(notContainedIn(b)).concat(b.filter(notContainedIn(a)));
}

Categories