How to display the array? - javascript

I have 3 arrays:
Array1 and Array2 have connections to each other:
var Array1 = ['Bob','James','Kanye','West'];
var Array2 = [0,1,2,3];
var Array3 = [1,3,0,2];
How do I display it to this?
Array4 = ['James', 'West', 'Bob','Kanye'];

you will require 2 loops, 1 will go through each element of Array3 and Second loop will be used to find the index value will be compared with Array2 to find index of Array 1 and then that index value will be saved in Array4 from Array1
for (var i = 0; i < Array3.length; i++)
{
var index = Array3[i];
var position=-1;
for(var j=0; j < Array2.length;j++)
{
if(index==Array2[j])
{
position = j;
break;
}
}
Array4[i] = Array1[j];
}

You need to run a loop over Array, take the integer inside as indexnumber, then you print out the first array with the numbers you just took from the first array.

You need to use -- and read the documentation for -- arrays' map method:
const names = ['Bob','James','Kanye','West'];
const order = [1,3,0,2];
const orderedNames = order.map(x => names[x]);
console.log(orderedNames);
// => ["James", "West", "Bob", "Kanye"]
Fiddle: https://jsfiddle.net/68hrrjx3/
Also kinda relevant in the context of the other answers: What is the difference between declarative and imperative programming

Related

How to get a value of column 'b' from a 2d array where column 'a' matches a single array in javascript

New to javascript. Need some guidance on the problem below:
I have these arrays:
array1 = [['a1'], ['a2'], ['a3']];
array2 = [['a1',4], ['a3',3], ['a6',2]];
How can i get the matching arrays whereby array1 first col = array2 first col?
Example expected result:
[['a1',4], ['a3',3]]
I hope the question makes sense. Not really sure how to approach this since the structure of these two arrays are different.
You can use filter to filter out the elements. Inside filter method check if elements exist in array1. You can flat array1 to check effeciently.
let flatArr1 = array1.flat(); //["a1", "a2", "a3"]
const result = array2.filter(([x,y]) => flatArr1.includes(x));
console.log(result) // for instance
This is my solution for your problem:
const compare = (array1, array2) => {
let matched = [];
const keys = [].concat(...array1);
for(let i = 0; i < array2.length; i++) {
for(let j = 0; j < array2.length; j++) {
let result = array2[i][j];
if(keys.includes(result)) {
matched.push(array2[i])
}
}
}
console.log("matched: ", matched);
};

comparing array of objects and assigning similarity score

I am attempting to compare two array of object and assigning them a similarity score based of common items in the array.
I was able to compare the arrays but I am running into issue with using the same concept on array of objects.
let array1 = [{key1:['item1','item2','item3','item4']},{key2:['event3','event4']}];
let array2 = [{key1:['item1','item4','item2','item8']},{key2:['event4','event2']}];
let arrayA=['item1','item2','item3','item4'];
let arrayB=['item1','item4','item2','item8'];
function SimilarityPercentage(arrayA,arrayB){
let answer =arrayA.filter(function(item) {
return arrayB.indexOf(item) >= 0;
}).length
return answer/(Math.max(arrayA.length,arrayB.length))*100
}
console.log(SimilarityPercentage(arrayA,arrayB));// 75
Given array1 and array2 , I would like the result split out a similarity score, similar to the function above. I would like to use the rand index calculation : https://en.wikipedia.org/wiki/Rand_index#targetText=The%20Rand%20index%20or%20Rand,is%20the%20adjusted%20Rand%20index.
You could get the values and calculate the common score.
function similarityPercentage(arrayA, arrayB) {
return 100 * arrayA.filter(Set.prototype.has, new Set(arrayB)).length / Math.max(arrayA.length, arrayB.length);
}
function similarities(a, b) {
var parts = a.map((o, i) => similarityPercentage(Object.values(o)[0], Object.values(b[i])[0]));
return parts.reduce((a, b) => a + b, 0) / parts.length;
}
var array1 = [{ key1: ['item1', 'item2', 'item3', 'item4'] }, { key2: ['event3', 'event4'] }],
array2 = [{ key1: ['item1', 'item4', 'item2', 'item8'] }, { key2: ['event4', 'event2'] }],
arrayA = ['item1', 'item2', 'item3', 'item4'],
arrayB = ['item1', 'item4', 'item2', 'item8'];
console.log(similarityPercentage(arrayA, arrayB)); // 75
console.log(similarities(array1, array2)); // 62.5
You could do something like this:
var array1 = [val1,val2,val3];
var array2 = [val1,val4,val5];
var sim = [];
var simscore = 9;
if (array1.length > array2.length) {
for (var i = 0; i < array1.length; i++) {
if(array1[i] == array2[i]) {
sim.push(i);
simarr = array1;
simscore ++;
}
}
}else{
for (var i = 0; i < array2.length; i++) {
if(array1[i] == array2[i]) {
sim.push(i);
simarr = array2;
simscore ++;
}
}
}
console.log(sim);
console.log("Percent similar: ", simscore/simarr.length);
This will add the similar index to an array sim and increase the count of similar indexes by 1, always for the longer array, then print the percent of similarity.
First of all, your sample arrays are not well-structured, and your problem can be done more quickly if you restructure them.
Since you have not provided a formula for calculating the similarity between array1 and array2, I assume that every each of these arrays has equal length, and every item in them represents an object which has only one property (with the same name), and that property itself is an array. One obvious approach is to calculate every similarity score of the related child arrays of these two arrays to be calculated and then calculate the total similarity by averaging every key's similarity score.
Assumptions:
array1 and array2 have equal length
The nth element of array1 has only one property with the name keyFoo and the nth element of array2 also has only one property with the name keyFoo and keyFoo property of these two arrays are arrays themselves and must be compared to each other.
This quickly can be done using already provided SimilarityPercentage function:
function SimilarityPercentage2 (array1, array2) {
let similaritySum = 0;
for (let i = 0; i < array1.length; i++) {
const elem = array1[i];
const key = Object.keys(elem)[0];
similaritySum += SimilarityPercentage(elem[key], array2[i][key]);
}
return similaritySum / array1.length;
}
console.log(SimilarityPercentage2(array1, array2));
// output: 62.5

Check whether elements from one array are present in another array

What is the best way to check whether elements from one array are present in another array using JavaScript?
I come up with two of the following methods (but neither of them do I like very much).
Method1
for(let i = 0; i < arr1.length; ++i) {
for(let j = 0; j < arr2.length; ++j) {
if(arr1[i] === arr2[j]) {
arr1[i].isPresentInArr2 = true;
break;
}
}
}
Method2
const idToObj = {};
for(let i = 0; i < arr2.length; ++i) {
nameToObj[arr2[i].Id] = arr2[i];
}
for(let i = 0; i < arr1.length; ++i) {
if(nameToObj[arr1[i].Id]) {
nameToObj[arr1[i].Id].isPresentInArr2 = true;
}
}
Here I am assuming that I have two arrays of objects: arr1 and arr2. Those objects have a unique Id property each. And I am to check whether every object in arr1 is present in arr2.
I suppose the second method would be more efficient. Hope for interesting suggestions.
in terms of Algorithm Complexity wise , It's like trade-offs .
First One - Space time Complexity - 0, Run time complexity - 0(n2)
Second One - Space time Complexity - o(n), Run time complexity - 0(n)
If it's performance focussed , go for second one .
In terms of js way , you have many ways . Read about includes() and indexOf() inbuilt method in javascript to avoid writing a loop . Also make use of javascript map function . You could also uses underscore.js
Ref Check if an array contains any element of another array in JavaScript for more details .
You could sort the arrays, then check if they are equal to one another:
var array1 = [4, 304, 2032], // Some random array
array2 = [4, 2032, 304];
function areEqual(array1, array2) {
if (array1.sort().toString() == array2.sort().toString()) {
// They're equal!
document.getElementById("isEqual").innerHTML = ("Arrays are equal");
return true;
} else {
// They're not equal.
document.getElementById("isEqual").innerHTML = ("Arrays aren't equal");
return false;
}
}
areEqual(array1, array2);
<!DOCTYPE html>
<html>
<body>
<p id="isEqual"></p>
</body>
</html>
You could get a list of Ids, then sort the id's and compare the two array lists of Ids using JSON.stringify
// Test arrays to work with
const array1 = [{Id:10},{Id:11},{Id:13},{Id:12}]
const array2 = [{Id:10},{Id:11},{Id:12},{Id:13}]
const array3 = [{Id:10},{Id:11},{Id:12}]
function test(arr1, arr2) {
// Map of each array [0, 1, 2, etc...]
let map1 = arr1.map(i => i.Id)
let map2 = arr2.map(i => i.Id)
// Sort each array from lowest to highest
// Note: Some kind of sort is required if we are going to compare JSON values
map1.sort()
map2.sort()
// Test the mapped arrays against each other
return JSON.stringify(map1) === JSON.stringify(map2)
}
console.log(test(array1, array2))
console.log(test(array1, array3))
map over the arrays of objects to produce arrays of ids, then use every and includes to check the elements in one array against the elements of the other: ids1.every(el => ids2.includes(el)).
Here's a working example:
const arr1 = [{ id: 0 }, { id: 1 }, { id: 2 }];
const arr2 = [{ id: 0 }, { id: 1 }, { id: 2 }];
const arr3 = [{ id: 14 }, { id: 1 }, { id: 2 }];
const getIds = (arr) => arr.map(el => el.id)
function check(arr1, arr2) {
const ids1 = getIds(arr1);
const ids2 = getIds(arr2);
return ids1.every(el => ids2.includes(el));
}
console.log(check(arr1, arr2));
console.log(check(arr1, arr3));

push more than one elements at same index in array

how to push more than one element at one index of a array in javascript?
like i have
arr1["2018-05-20","2018-05-21"];
arr2[5,4];
i want resulted 4th array to be like:
arr4[["2018-05-20",5],["2018-05-21",4]];
tried pushing like this:
arr1.push("2018-05-20","2018-05-21");
arr1.push(5,4);
and then finally as:
arr4.push(arr1);
But the result is not as expected. Please someone help.
Actually i want to use this in zingChart as :
Options Data
Create an options object, and add a values array of arrays.
Calendar Values
In each array, provide the calendar dates with corresponding number values in the following format.
options: {
values: [
['YYYY-MM-DD', val1],
['YYYY-MM-DD', val2],
...,
['YYYY-MM-DD', valN]
]
}
Your question is not correct at all, since you cannot push more than one element at the same index of an array. Your result is a multidimensional array:
[["2018-05-20",5],["2018-05-21",4]]
You have to create a multidimensional array collecting all your data (arrAll)
Then you create another multidimensional array (arrNew) re-arranging previous data
Try the following:
// Your Arrays
var arr1 = ["2018-05-20","2018-05-21"];
var arr2 = [5, 4];
//var arr3 = [100, 20];
var arrAll = [arr1, arr2];
//var arrAll = [arr1, arr2, arr3];
// New Array definition
var arrNew = new Array;
for (var j = 0; j < arr1.length; j++) {
var arrTemp = new Array
for (var i = 0; i < arrAll.length; i++) {
arrTemp[i] = arrAll[i][j];
if (i === arrAll.length - 1) {
arrNew.push(arrTemp)
}
}
}
//New Array
Logger.log(arrNew)
Assuming the you want a multidimensional array, you can put all the input variables into an array. Use reduce and forEach to group the array based on index.
let arr1 = ["2018-05-20","2018-05-21"];
let arr2 = [5,4];
let arr4 = [arr1, arr2].reduce((c, v) => {
v.forEach((o, i) => {
c[i] = c[i] || [];
c[i].push(o);
});
return c;
}, []);
console.log(arr4);

Convert every nth element of an array to an object in javascript

I'd like to convert:
var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"]
into:
var rows = [
[1, "Shaw", "Tanzania"],
[2, "Nelson", "Kazakhstan"],
[3, "Garcia", "Madagascar"]
];
I've seen this answer to a similar question, but I don't understand how that works and extend it to every nth element
Use a for loop with Array#slice. You iterate the original array using the require chunk size as the step. On each iteration you slice the relevant part from the original array (slice doesn't mutate the array), and push it into the result array.
var people = [1,"Shaw","Tanzania",2,"Nelson","Kazakhstan",3,"Garcia","Madagascar"];
var result = [];
var chunkSize = 3;
for(var i = 0; i < people.length; i+= chunkSize) {
result.push(people.slice(i, i + chunkSize));
}
console.log(result);

Categories

Resources