Empty all elements in array with pop method - javascript

I am trying to empty an array by using the pop method after that I want to push the returned result of the pop method to another array and get the full result, but the pop method doesn't satisfy my needs it always stops midway what is the problem?
let arr = [1,2,3,4,5,6,7]
let newArr = []
//console.log(arr.pop())
const fib = function(n){
if(n <= arr.length){
newArr.push(arr.pop())
return fib(n+1)
}
}
fib(0)
console.log(newArr)

I would do like that:
var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = [];
while(myArr.length){
myNewArr.push(myArr.pop());
}
console.log(myArr, myNewArr);
If you just want to reverse it you could use the reverse function for Arrays:
var myArr = [1,2,3,4,5,6,7,8,9];
myArr = myArr.reverse();
console.log(myArr);
// Or if you really need 2 variables and one needs to be empty
var myArr = [1,2,3,4,5,6,7,8,9];
var myNewArr = myArr.reverse();
myArr = [];
console.log(myArr, myNewArr);

let arr = [1,2,3,4,5,6,7]
let newArr = []
//console.log(arr.pop())
const fib = function(n){
if(!n <= 0){
newArr.push(arr.pop())
return fib(n-1)
}
}
fib(arr.length)
console.log(newArr)

If you want your array empy... I think this is the easiest way.
var array = [1,2,3,4,5,6,7]
array = []
console.log(array)

Related

Find Missing levels and fill it

I have two arrays and need to fill the missing values with NA by comparing the levels present in other array. I used the arr.find to search but not sure how to proceed further.
Input:
const levels = [1,2,3,4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
Output:
out = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":2,"NAME1":"NA"},{"LEVEL":3,"NAME1":"TOM"},{"LEVEL":4,"NAME1":"NA"}]
Code:
let presentLevels = [];
for (let i = 1; i <= levels.length; i++) {
let check = arr.find(p => p['LEVEL'] === levels[i])
if (check) {
presentLevels.push(i)
}
}
console.log(presentLevels)
You can use map() the levels array. Find the object with LEVEL equal to the current element. If you find an object then just return that otherwise return a new object with LEVEL and NAME1 props
const levels = [1,2,3,4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
const res = levels.map(x => (arr.find(a => a.LEVEL === x) || {level: x, NAME1: "NA"}));
console.log(res)
Using Array.find() inside a loop might cause a performance issue if the arr is large enough. I would create a Map of existing levels by LEVEL, and then use the Map to get the existing levels.
Since you want the presentLevels array to be ordered by the number of the level, you'll need to iterate the levels array, and return a new array. You can do this easily with Array.map(). On each iteration take the current level from the existing Map, and if not found in existing return a new object with NA.
const levels = [1, 2, 3, 4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
const existingMap = new Map(arr.map(o => [o.LEVEL, o]))
const presentLevels = levels.map(LEVEL =>
existingMap.get(LEVEL) || { LEVEL, NAME1: 'NA' }
);
console.log(presentLevels)
You can make a loop with levels to get the items which arr doesn't have, then adding that items to arr
const levels = [1,2,3,4]
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}]
var items = levels.filter(level => !arr.find(item => item.LEVEL === level));
items.forEach(level => arr.push({LEVEL: level, NAME1: "NA"}));
console.log(arr.sort((a, b) => a.LEVEL - b.LEVEL));
You could first map the levels to the object array with all NA, and then iterate arr to replace those where necessary:
const levels = [1,2,3,4];
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}];
const result = levels.map(LEVEL => ({LEVEL, NAME1: "NA"}) );
for (let o of arr) result[o.LEVEL-1] = o;
console.log(result);
Although this executes two loops, they are not nested, and so this task is performed with linear time complexity (contrary to solutions that have a find call inside the loop).
maybe like this:
const levels = [1,2,3,4];
const arr = [{"LEVEL":1,"NAME1":"JACK"},{"LEVEL":3,"NAME1":"TOM"}];
for(var key_l in levels){
var found_levels = false;
for(var key_ar in arr){
if(arr[key_ar].LEVEL == levels[key_l]){
found_levels = true;
}
}
if(!found_levels){
arr.push({"LEVEL":levels[key_l],"NAME1":"NA"});
}
}
/* for result sorting, if need... */
arr.sort(function(a, b){
return a.LEVEL > b.LEVEL;
});
console.log(arr);

How can I push all array variables of N arrays in just one array over an loop function?

I have an problem to figure out how to write code in JavaScript for that:
i have many arrays -> 1 to N arrays like that
let array_0 = ["a","b","f"];
let array_1 = ["c","b","g","r"];
let array_2 = ["a","b","f","2","43"];
..to N..
let array_N = ["a","a","s","d"];
at next i need all the variables in just one array like that:
let array_fin = ["a","b","f","c","b","g","r","a","b","f","2","43","a","a","s","d"];
or over the console.log() -> 0: ["a","b","f","c","b","g","r","a","b","f","2","43","a","a","s","d"];
but over an loop function for all array_N's
I tried to do that over the map() function, but the map function gives me an array like that:
0: ["a","b","f"]
1: ["c","b","g","r"]
2: ["a","b","f","2","43"]
..
N
but that's not what I need and I couldn't figure out which command could do that.
I tried also an function like push(), but I could not figure out how to call that over an loop function to handle N array's.
If you don't want to type them all out, just make them global variables using var and join them using spread syntax ...array_N and a while-loop:
var array_0 = ["a","b","f"];
var array_1 = ["c","b","g","r"];
var array_2 = ["a","b","f","2","43"];
var array_3 = ["a","a","s","d"];
let result_array = [];
let i = -1;
while (window[`array_${++i}`] instanceof Array) {
result_array = [...result_array, ...window[`array_${i}`]];
}
console.log(result_array);
And yes, this will work for 1500+ Arrays, too :)
Just use concat() to merge all your arrays like this:
let array_0 = ["a","b","f"];
let array_1 = ["c","b","g","r"];
let array_2 = ["a","b","f","2","43"];
let array_N = ["a","a","s","d"];
let array_fin = array_0.concat(array_1, array_2, array_N);
console.log(array_fin);
Solution using Array#filter and eval. Not recommend to be used, since eval has security issues. Just for knowledge that this is also possible.
let array_0 = ["a","b","f"];
let array_1 = ["c","b","g","r"];
let array_2 = ["a","b","f","2","43"];
const res = [];
for(let i = 0;;i++){
try {
const arr = eval(`array_${i}`);
res.push(...arr.filter(a=>!res.includes(a)));
} catch(e){
console.log(e.message);
break;
}
}
console.log(res);
Why not to use eval
You can access the window object in order to access global variables (i.e the arrays) and make a loop for concatenate they, as shown on next example:
var array_0 = ["a","b","f"];
var array_1 = ["c","b","g","r"];
var array_2 = ["a","b","f","2","43"];
var array_3 = ["a","a","s","d"];
// Create the array of all arrays.
let numOfArrays = 4;
var array_all = [];
for (i = 0; i < numOfArrays; i++)
{
array_all = array_all.concat(window['array_' + i]);
}
console.log(array_all);

Javascript check if any of the values exist on array of objects [duplicate]

I have one array like this one:
array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}]
I have a second array of integer :
array2=[1,3]
I would like to obtain this array without a loop for :
arrayResult = ['value1', 'value3']
Does someone know how to do it with javascript ?
Thanks in advance
Map the elements in array2 to the label property of the element in array1 with the corresponding value:
array2 // Take array2 and
.map( // map
function(n) { // each element n in it to
return array1 // the result of taking array1
.find( // and finding
function(e) { // elements
return // for which
e.value // the value property
=== // is the same as
n; // the element from array2
}
)
.label // and taking the label property of that elt
;
}
)
;
Without comments, and in ES6:
array.map(n => array1.find(e => e.value === n).label);
You can use .filter and .map, like this
var array1 = [
{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}
];
var array2 = [1, 3];
var arrayResult = array1.filter(function (el) {
return array2.indexOf(el.value) >= 0;
}).map(function (el) {
return el.label;
});
console.log(arrayResult);
A simple for-loop should suffice for this. In the future you should seriously post some code to show what you have tried.
var array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}];
var array2=[1,3];
var result = [];
for (var i = 0; i < array2.length; i++){
result.push(array1[array2[i]-1].label);
}
console.log(result); //["value1", "value3"]
JSBIN
Good answers all. If I may suggest one more alternative using Map as this seems to be suited to a key:value pair solution.
var arr1 = [ {value:1, label:'value1'}, {value:2, label:'value2'}, {value:3, label:'value3'} ];
var arr2 = [1, 3];
// create a Map of the first array making value the key.
var map = new Map( arr1.map ( a => [a.value, a.label] ) );
// map second array with the values of the matching keys
var result = arr2.map( n => map.get ( n ) );
Of course this supposes that the key:value structure of the first array will not become more complex, and could be written in the simpler form of.
var arr1 = [[1,'value1'], [2,'value2'], [3,'value3']]; // no need for names
var arr2 = [1, 3];
var map = new Map( arr1 ); // no need to arr1.map ;
var result = arr2.map( n => map.get ( n ) );
Just index the first array using the _.indexBy function:
var indexedArray1 = _.indexBy(array1, "value");
_.map(array2, function(x) { return indexedArray1[x].label; });

Sorting a multidimensional array in javascript?

I am new to programming and I have just worked out a multidimensional array problem by using pure javascript but I think I made it too complicated and just wondering can anyone tell me how do you think about my method and do you have a better way to do it.
the problem is to console.log all the numbers in the arrays and the array is [[[1,2],[3,4]],[[5,6]]]. My code is as below, please post your suggestions,thanks
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
var nestedArrOne = nestedArr[0];
var nestedArrTwo = nestedArr[1];
var newArr = nestedArrOne.concat(nestedArrTwo);
function showAll(){
for(var i=0; i<newArr.length; i++){
for(var j=0; j<newArr[i].length; j++){
console.log(newArr[i][j]);
}
}
}
showAll();
You could iterate the nested array and check if the item is an array, then call the function again for the inner array.
function iter(array) {
var i; // declare index
for (i = 0; i < array.length; i++) { // iterate array
if (Array.isArray(array[i])) { // check if item is an array
iter(array[i]); // if so, call iter with item
continue; // and continue the loop
}
console.log(array[i]); // the wanted output
}
}
var nestedArr = [[[1, 2], [3, 4]], [[5, 6]]];
iter(nestedArr);
The recursive function could be used to flatten the array.
let isArray = val => val.constructor === Array
let log = val => console.log(val)
let flatten = val =>
val
.reduce((acc, cur) =>
isArray(cur) ? [...acc, ...flatten(cur)] : [...acc, cur],
[])
// Running examples
let arrA = [[[1,2],[3,4]],[[5,6]]]
flatten(arrA).forEach(log)
log('-------------------')
let arrB = [[[1,2],[3,4]],[[5,6]],[7],[[[[9]]]]]
flatten(arrB).forEach(log)
A fancy Haskellesque approach with "pattern matching by rest operator" could be.
var flat = ([x,...xs]) => x ? [...Array.isArray(x) ? flat(x) : [x], ...flat(xs)] : [];
na = [[1,2],[3,[4,5]],[6,7,[[[8],9]]],10];
fa = flat(na);
console.log(...fa);

Sorting an array by another index array

I'm iterating over array couples and I need to sort one by the order of the other.
Say I have these two arrays:
aLinks = [4,5,6]
bLinks = [1,2,3,4,5,6]
I need to return:
aLinks = [4,5,6]
bLinks = [4,5,6,1,2,3]
meaning that i need to have the items that match first array first and than the rest,
sorted by order if possible.
I'm working with d3 so I'm using forEach to go through the link sets and save the order of aLinks.
I don't know how to apply this order to bLinks
var linkOrder = [];
linkSets.forEach(function(set, i) {
linkOrder = [];
set.aLinks.forEach(function(link,i){
linkOrder.push(link.path);
})
});
You can do it like:
Take out the matching items from second array into a temp array
Sort the temp array
Sort the second array containing only items that did not match
Concatenate the second array into the temp array
Code - With the fix provided by User: basilikum
var first = [4,5,6];
var second = [1,7,3,4,6,5,6];
var temp = [], i = 0, p = -1;
// numerical comparator
function compare(a, b) { return a - b; }
// take out matching items from second array into a temp array
for(i=0; i<first.length; i++) {
while ((p = second.indexOf(first[i])) !== -1) {
temp.push(first[i]);
second.splice(p, 1);
}
}
// sort both arrays
temp.sort(compare);
second.sort(compare);
// concat
temp = temp.concat(second);
console.log(temp);
Working Demo: http://jsfiddle.net/kHhFQ/
You end up with A + sort(A-B) - so you just need to compute the difference between the 2 arrays. Using some underscore convenience methods for example:
var A = [4,5,6];
var B = [1,2,3,4,5,6];
var diff = _.difference(A,B);
var result = _.flattern(A, diff.sort());
iterate the first array, removing the values from the second array and then appending them to the start of the array to get the right order :
var arr1 = [4,5,6];
var arr2 = [1,2,3,4,6,5];
arr1.sort(function(a,b) {return a-b;});
for (i=arr1.length; i--;) {
arr2.splice(arr2.indexOf(arr1[i]), 1);
arr2.unshift( arr1[i] );
}
FIDDLE

Categories

Resources