I am trying to create an object from 2 arrays.
var arr1 = ["2000", "10003", "1234000", "44444444", "9999", "11", "11", "22", "123"];
var arr2 = [2, 4, 10, 32, 36, 2, 2, 4, 6];
I used a for loop to populate the object:
var obj= {};
for(var i = 0; i < arr1.length; i++) {
obj[arr1[i]] = arr2[i];
}
Result:
[object Object] {
10003: 4,
11: 2,
123: 6,
1234000: 10,
2000: 2,
22: 4,
44444444: 32,
9999: 36
}
It does create the object based on my 2 arrays, but omit 1 value that is a duplicate in the arrays. I don't want to exclude them. What could be the trick to include ALL the array element in my object? The result is not even in the same order as the original arrays...
Thank you!
populate the values into array if that could be a workaround for you..
var obj= [];
for(var i = 0; i < arr1.length; i++) {
var obj1 ={};
obj1[arr1[i]] = arr2[i];
obj.push(obj1);
}
Related
This question already has answers here:
Looping through array and removing items, without breaking for loop
(17 answers)
Closed 5 months ago.
let arr = [1, "5", 3, 27, undefined, { name: 'Steven' }, 11];
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] !== 'number') {
arr.splice(i, 1);
}
}
console.log(arr); // output is: [1, 3, 27, {…}, 11]
If I swap the places of the object and the last number output is different.
let arr = [1, "5", 3, 27, undefined, 11, { name: 'Steven' }];
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] !== 'number') {
arr.splice(i, 1);
}
}
console.log(arr); // output is: [1, 3, 27, 11]
Can anyone explain why?
You shouldn't mutate an arrays length while you are iterating over it. Would recommend you use filter
For example i have a array like that
var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];
for (var i = 0;i < myArray.length;i++){
for(var j = 0 ;j< myArray[i].length;j++){
for(var k = 0;k< myArray[i][j].length;k++){
console.log(myArray[i],[j][k]);
}
}
}
But output is only 11,12,13,14,15.
And i wanna print all the values
Could some one help to fix
Thank you in advance
Use e.g. Array.prototype.flat(), .flat(2) flattens to the level of 2 arrays deep.
var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];
console.log(myArray.flat(2));
You can use recursive function
first pass it the whole array then loop it and check if the element you are accessing is array or digit
if its array call the same function again and only pass it this element
otherwise if its digit just print it
This works even when you dont know how many nested arrays you have otherwise use MWO answer
var myArray = [
[1,2,3],
[4,5,6],
[7,8,9,10],
[[11,12],[13,14,15]]];
function printArray(arr){
for(var i = 0; i < arr.length; i++){
if(Array.isArray(arr[i])){
printArray(arr[i]);
}else{
console.log(arr[i]);
}
}
}
printArray(myArray);
This fucntion works for any depth of multi dimensional array. Using Recursion
var myArray = [1,2,33,44, [1,2,3], [[11,12],[13,14,15]]];
var myArray1 = [1,2,33,44, [[11,12],[13,14,15]]];
var deepFlattenArray = function (array){
var result = [];
array.forEach(function (element) {
if (Array.isArray(element)) {
result = result.concat(deepFlattenArray(element));
} else {
result.push(element);
}
});
return result;
};
console.log(deepFlattenArray(myArray));
// output = [ 1, 2, 33, 44, 1, 2, 3, 11, 12, 13, 14, 15]
console.log(deepFlattenArray(myArray1));
// output = [1, 2, 33, 44, 11, 12, 13, 14, 15 ]
I am writing an algorithm for finding two elements in an array that sums up to the provided value. i.e for array [2, 7, 5, 3, 4, 11, 12, 56] and value 9 I am finding two elements for eg. 2 and 7 which adds to our provided value 9. I am getting the final result as [ [ 2, 7 ], [ 4, 5 ] ]. Please find the code below
const getSumOfValuesInArr = (arr, val) => {
var result = [];
for (var i = 0; i < arr.length; i++) {
for (var j = i; j < arr.length; j++) {
if (arr[j] + arr[i] === val) {
result.push([arr[i], arr[j]]);
}
}
}
console.log(result);
return result;
};
getSumOfValuesInArr([2, 7, 5, 3, 4, 11, 12, 56], 9);
But as you can it is a bit expensive. How can I write a better algorithm for better performance? Please help.
You could take a single loop and store seen values in a hash table.
Then check if the delta of the wanted sum and the actual value is seen before then add the pair to the result set.
const getSumOfValuesInArr = (arr, val) => {
var result = [],
seen = {};
for (let i = 0; i < arr.length; i++) {
if (seen[val - arr[i]]) result.push([val - arr[i], arr[i]]);
seen[arr[i]] = true;
}
return result;
};
console.log(getSumOfValuesInArr([2, 7, 5, 3, 4, 11, 12, 56], 9));
This question already has answers here:
Delete from array in javascript
(4 answers)
Closed 5 years ago.
Trying to make a function that removes only the "strings" from the array. I'm looking to only have the numbers left. I've already accomplished this by adding numbers only to a newArray, and I was looking into the splice method but could not figure out how to write it. As you see in code delete works, but returns undefined in its spot.
function numbersOnly(arr){
for(var i = 0; i < arr.length; i++){
if(typeof arr[i] === "string"){
delete arr[i];
}
}
console.log(arr);
}
numbersOnly([1, "apple", -3, "orange", 0.5, 22, "hello", 6])
returns [1, undefined, -3, undefined, 0.5, 22, undefined, 6]
var arr = [1, "apple", -3, "orange", 0.5, 22, "hello", 6];
var out = arr.filter(function(f) { return typeof(f) !== 'string';});
console.log( out );
If you delete sth in an array, there stays an empty space which is undefined. You need to shift the array, so replace
delete arr[i];
with
arr=arr.slice(0,i).concat(arr.slice(i+1));
i--;
or using splice:
arr.splice(i,1);
i--;//dont jump over this index
or using a for loop:
for(var b=i;b<arr.length-1;b++){
arr[b]=arr[b+1];
}
arr.length-=1;
i--;
Alternatively you could filter:
arr.filter(el=>typeof el==="number");//numbers only
//or
arr.filter(el=>typeof el!=="string");//not stringd
You would want to use array.splice() instead of delete, which is for properties.
I would have a go another way around
function numbersOnly(arr){
let numbers = [];
for(var i = 0; i < arr.length; i++){
if(typeof arr[i] === "number"){
numbers.push(arr[i]);
}
}
console.log(numbers);
}
use .splice(index, count)
function numbersOnly(arr) {
for(var i = 0; i < arr.length; i++) {
if(typeof arr[i] === "string") {
arr.splice(i, 1);
}
}
console.log(arr);
}
numbersOnly([1, "apple", -3, "orange", 0.5, 22, "hello", 6]);
If the array's cell contains a number and that number yields true for if Number(). Then that value will be added to a secondary array and returned.
function numbersOnly(arr){
var numbersarr = [];
var i;
var k = 0;
for (i=0; i< arr.length ;i++) {
if ( Number(arr[i]) ) {
numbersarr[k++] = arr[i];
}
}
console.log(numbersarr);
return numbersarr;
}
var strarr = [1, "apple", -3, "orange", 0.5,
22, "hello", 6 , "car", "123" ,
"zoo", "456"];
numbersOnly(strarr);
numbersOnly(["foo","bar", "something"]);
And this is how your output will be:
[1, -3, 0.5, 22, 6, "123", "456"]
I've been working with arrays and what I want is to create a formula that will allow me to loop over an array that contains objects and take keys with different values and turn them into a multi-dimensional array (I need to keep the order of the keys). I'm already getting this array but now I need to add ['n/a', '--'] on every position where the strings are not the same, like this:
var all = [
{banana: 1, rose: 2, mouse: 9, apple: 5, ana: 4, carl: 'truck'},
{banana: 1, rock: 58, car: 19, apple: 5, cheese: 3, carl: 'blue'},
{banana: 1, cheese: 2, red: 14, clue: 89, apple: 5, ana: 8}
];
//expected to get:
var new-arr = [ [["ana", 4], ["n/a", "--"], ["carl", "truck"]],
["n/a", "--"], ["cheese", 3], ["carl", "blue"]],
[["ana", 8], ["cheese", 2], ["n/a", "--"]] ];
So that at the end I cna create a list like this
list1:
ana: 4
n/a: --
carl: truck
list2:
n/a: --
cheese: 3
carl: blue
list2:
ana: 8
cheese: 2
n/a: --
The code is here
https://jsbin.com/yedusigara/1/edit?js,console
Did I do something wrong? Is there any way I can do it all in one function?
Your bug is not shown in the question, but it is in the fiddle, in this portion:
$('.lol').each(function (i, elm) {
similar_keys[i].forEach(function(spec, j){
similar_keys[j].forEach(function (spec1, j1){
if(spec[0] != spec1[0] && j != j1){
similar_keys[i].push(['n/a', '--']);
}
});
it doesn't make any sense to iterate through similar_keys[j] on the 3rd loop. j is an index of the inner array. This code just makes no sense. You even rely on having the same number of elements in the DOM and objects in your data.
I can only guess at what you are trying to accomplish, but I would modify your original algorithm instead. Maybe this:
function similars(arr) {
var similar_keys = [];
for (var i = 0; i < arr.length; i++) {
var tempArr = [];
for (var key in arr[i]) {
var found = false;
var count = 0;
var index = 0;
for (var j = 0; j < arr.length; j++) {
if (arr[j].hasOwnProperty(key)) {
++count;
}
if (i !== j && arr[j][key] === arr[i][key]) {
found = true;
break;
}
}
if (!found && count > 1) {
tempArr.push([key, arr[i][key]]);
}
else if (count > 1) {
tempArr.push(["N/A", arr[i][key]]);
}
}
similar_keys.push(tempArr);
}
return similar_keys;
}
EDIT:
Still not sure what you are looking for. What I think you need to do:
1) Sort each of the rows in similar_keys by the first element
2) Compare first element of each row, and insert the N/A entry to the row with the lowest sort order.
3) continue through each column, inserting as necessary.
i will try to modify your fiddle to demonstrate
EDIT:
this should work.
https://jsbin.com/nesiqogebo/edit?js,console,output