How to create many elements and add them to another many elements? - javascript

Hi i have problems with creating many elements and adding to them many elements and then append them to another elements.
my code looks like this:
const createElementsFromLocalStorage = (event) => {
for (let i = 0; i < allRecipes.length; i++) {
let optionValue = document.createElement('option');
optionValue.value = allRecipes[i].title;
for(let j = 0; j < allDaysDataLists; j++) {
allDaysDatalists[j].appendChild(optionValue);
}
}
}
So i want to create optionValue "i" times and set them values with each allRecipes.title. It should looks like this for example:
I have array allRecipes = [1, 2, 3, 4, 5]
So I want to create 5 times optionValue and each optionValue should have .value depends on array index. For example: optionValue.value = 1, optionValue.value = 2, optionValue.value = 3, optionValue.value = 4, optionValue.value = 5. Then I want to append all this optionValue elements to each allDaysDataLists. So each allDaysDataLists should have all this created optionValue.

for(let i = 0; i < allDaysDataLists.length; i++) {
for(let j = 0; j < allRecipes.length; j++) {
const optionValue = document.createElement('option');
optionValue.value = allRecipes[j].title;
allDaysDatalists[i].appendChild(optionValue);
}
}

can you try this?
const createElementsFromLocalStorage = (event) => {
allRecipes.forEach(r => {
allDaysDatalists.forEach(select => {
select.options[select.options.length] = new Option(r.title, r.title);
});
});
}

Related

javascript: array sort data become weird

previously i've do some technical test with hackerrank. For the simple testing i need to make two different array so i can check it the difference both of them. the first array will be unsorted, and the second will be sorted.
Here's my code:
function dataSort(thedata) {
// Write your code here
var unsorted = thedata
var sorted = thedata
console.log("not sorted", unsorted) // first log
for(let i = 0; i < sorted.length; i++)
{
for(let j = i; j < sorted.length; j++)
{
if(sorted[i] > sorted[j])
{
let temp = sorted[i]
sorted[i] = sorted[j]
sorted[j] = temp
}
}
}
console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])
above code given the result below
not sorted [ 1, 3, 4, 2, 1 ]
sorted [ 1, 1, 2, 3, 4 ]
Okay, that's seems have no problem. but when i move the first console after the bubble sort near with second console, the data also sorted
function dataSort(thedata) {
// Write your code here
var unsorted = thedata
var sorted = thedata
for(let i = 0; i < sorted.length; i++)
{
for(let j = i; j < sorted.length; j++)
{
if(sorted[i] > sorted[j])
{
let temp = sorted[i]
sorted[i] = sorted[j]
sorted[j] = temp
}
}
}
console.log("not sorted", unsorted) // first log
console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])
result
not sorted [ 1, 1, 2, 3, 4 ]
sorted [ 1, 1, 2, 3, 4 ]
Can you tell me what happened?
GrafiCode gave you the correct explanation about why this happens.
Here is a possible solution:
function dataSort(thedata) {
// Write your code here
var unsorted = new Array(...thedata)
var sorted = new Array(...thedata)
for(let i = 0; i < sorted.length; i++)
{
for(let j = i; j < sorted.length; j++)
{
if(sorted[i] > sorted[j])
{
let temp = sorted[i]
sorted[i] = sorted[j]
sorted[j] = temp
}
}
}
console.log("not sorted", unsorted) // first log
console.log("sorted",sorted) // second log
}
dataSort([1,3,4,2,1])

I'm trying to exclude elements from an Array, but I'm doing somthing wrong

I'm trying to create this script: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy
After the comment "Verify and delete" is where I have the problem.
I try to check all the elements form the array 'theCheck' with the elements from 'destroyers' and if the elements dont match then the script will push that value to the output array.
But it pushes every element regardless.
Expected output value: [1,1]
Current output value value: [1,2,3,1,2,3]
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] !== destroyers[j]) {
output.push(theCheck[i])
break;
}
}
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
With the current code you're looping through the destroyers and anytime you find a destroyer that doesn't match the item you're checking you're adding it to the output. But because you've got two items in the destroyers array it is guaranteed that one of the two is not going to match the particular item that you're checking.
Below is a version where we work out whether any of the destroyers are found to match the item that we're checking, and only if it doesn't we're adding it to the output:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
let found = false;
for (j = 0; j < destroyers.length; j++) {
if (theCheck[i] === destroyers[j]) {
found = true;
}
}
if(!found) output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
You could use the includes function to tidy this up a little:
function destroyer(arr) {
let theCheck = [];
let destroyers = [];
let output = [];
for (let i = 1; i < arguments.length; i++) {
destroyers.push(arguments[i]);
}
for (let i = 0; i < arguments[0].length; i++) {
theCheck.push(arguments[0][i])
}
//Verify and delete
var j = 0
for (let i = 0; i < theCheck.length; i++) {
if(!destroyers.includes(theCheck[i]))
output.push(theCheck[i]);
}
console.log(theCheck)
console.log(destroyers)
console.log(output)
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(input, ...arr) {
return input.filter(element => !arr.includes(element));
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));

Compare Arrays with Javascript and build another Array

In Javascript:
I have an existing array like [4,5,6,10] - (These are 'repid').
I have an ajax response like [{"repid":5,"avgAmount":2.5},{"salesrepid":10,"avgAmount":3.0}].
I have to build a third array which will compare the 'repids' of the 2 arrays and build a third array so that it will place a '0' if the repids do not match or else the 'avgAmount' if they match.
So, in my case above, I would 'build' a third array:
[0, 2.5, 0, 3.0]
I've tried many variances of:
//need to assign the sales average values to the proper repid
for (var i = 0; i < repIds.length; i++) {
for (var j = 0; j < salesrepids.length; j++) {
if (repIds[i] == salesrepids[j]) {
salesvalues.push(key.avgAmount);
} else { salesvalues.push("0"); }
};
}
}
}
You need to address the correct keys of your objects. And also only add the 0 in case you don't find any matching entry:
var repIds = [4, 5, 6, 10];
var salesrepids = [{"repid": 5, "avgAmount": 2.5}, {"repid": 10, "avgAmount": 3.0}]
var salesvalues = [];
for (var i = 0; i < repIds.length; i++) {
var noMatch = true;
for (var j = 0; j < salesrepids.length; j++) {
if (repIds[i] === salesrepids[j]['repid']) {
salesvalues.push(salesrepids[j]['avgAmount']);
noMatch = false;
}
}
if (noMatch) {
salesvalues.push(0);
}
}
console.log(salesvalues);
You can do something like using map and find:
Loop through the first array -> Check if the id exists in the second array using find -> If yes, return it's avgAmount else return 0.
const ids = [4,5,6,10],
amounts = [{"repid":5,"avgAmount":2.5},{"repid":10,"avgAmount":3.0}];
const output = ids.map(i => {
const found = amounts.find(a => a.repid === i);
return found ? found.avgAmount : 0;
})
console.log(output)
May be like this:
var repids = [4,5,6,10];
var returns = [{"repid":5,"avgAmount":2.5},{"salesrepid":10,"avgAmount":3.0}];
var results = [];
for(var key in returns){
if(repids.includes(returns[key].repid)){
results.push(returns[key].repid);
results.push(returns[key].avgAmount);
}
if(repids.includes(returns[key].salesrepid)){
results.push(returns[key].salesrepid);
results.push(returns[key].avgAmount);
}
}
console.log(results);

How to get subset of two arrays into a different array using javascript?

i have 2 arrays.
arr1=[1,8,1,3,2]
arr2=[3,8,1]
I want to put elements [8,1] subset into arr3. How can i do this using javascript?I used the following code. But doesn't seemed to be working.
function subsetFind() {
var arr1 = [1,8,1,3,2]
var arr2 = [3,8,1]
var arr3 = [];
var arr1length = arr1.length;
var arra2length = arr2.length;
for(var i = 0; i < arr1length; ++i){
for(var j=0;j<arra2length;j++) {
if(arr1[i] != arr2[j]) {
break;
} else {
arr3.push(arr1[i]);
break;
}
}
}
alert(arr3);
}
Try this solution - it checks whether both current and previous OR current and next value is equal:
function subsetFind() {
var arr1 = [1,8,1,3,2]
var arr2 = [3,8,1]
var arr3 = [];
var arr1length = arr1.length;
var arra2length = arr2.length;
var used_i = 0;
for(var i = 0; i < arr1length; ++i){
if(used_i != 0 && used_i < i-1){
break;
}
for(var j=0;j<arra2length;j++) {
if((arr1[i] == arr2[j] && arr1[i-1] == arr2[j-1]) || (arr1[i] == arr2[j] && arr1[i+1] == arr2[j+1])) {
arr3.push(arr1[i]);
used_i = i;
}
}
}
alert(arr3);
}
Output:
8,1
I hope that you want; (renewed :)
function subset() {
var arr1 = [1, 9, 3, 5, 4, 8, 2, 6, 3, 4]
var arr2 = [5, 2, 4, 8, 2, 6, 4]
var arr3 = [];
var minSize=2; // minimum 2 element must in intersection
var findedMax = "";
var arr1Joined = ""; arr1.forEach(function (a) { arr1Joined += "," + a; });
for(k=minSize;k<arr2.length;k++)
arr2.forEach(function (x,y) {
var fkey="";
for (i = y; i <= y+k; i++)
fkey += "," + arr2[i];
if (arr1Joined.indexOf(fkey) >= 0) findedMax = fkey;
});
arr3=findedMax.substr(1).split(",");
alert(arr3);
}
Try This Out:
Reference n-dru's answer:
function subset () {
var arr1 = [1,9,3,5,4,8,2,6,3,4]
var arr2 = [5,2,4,8,2,6,4]
var arr3 = [];
var arr1length = arr1.length;
var arra2length = arr2.length;
var finalResult;
for(var i = 0; i < arr1length; ++i){
for(var j=0;j<arra2length;j++) {
if((arr1[i] == arr2[j] && arr1[i-1] == arr2[j-1]) || (arr1[i] == arr2[j] && arr1[i+1] == arr2[j+1])) {
arr3.push(arr1[i]);
}
else
{
finalResult = arr3.toString();
}
}
}
alert(finalResult);
}
DEMO
I believe Your question was alredy answerd in: Simplest code for array intersection in javascript and Finding matches between multiple JavaScript Arrays . You can also look into implementation of _.intersection in lowdash library.
ES6 way.
[...new Set(arr1)].filter(v => arr2.includes(v))
Break down:
new Set(arr1) // convert arr1 to Set to remove duplicates
[...new Set(arr1)] // convert back to array
arr2.includes(v) // test if arr2 includes `v`
[...new Set(arr1)].filter(v => arr2.includes(v)) // choose unique elements in both arrays

Comparing and Filtering two arrays

I've been trying to implement a function where given with two arrays,
array1's elements is used as conditions to filter out elements in array2.
For instance:
array1= [apple, grapes, oranges]
array2= [potato, pears, grapes, berries, apples, oranges]
After feeding into a function, array2 should have elements as such:
filter_twoArrays(array1,array2)
array2= [grapes, apples, oranges]
I've tried the following code, using for loops and array.splice(), but the problem I am seeing is that when I use the splice method, it seems that it changes the lengths of array2 in the for loop:
function filter_twoArrays(filter,result){
for(i=0; i< filter.length; i++){
for(j=0; j< result.length; j++){
if(filter[i] !== result[j]){
result.splice(j,1)
}
}
}
Any inputs will be greatly appreciated on how to refine the filter function
cheers!
You can use filter as follow
var array1 = ['apples', 'grapes', 'oranges', 'banana'],
array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];
var intersection = array1.filter(function(e) {
return array2.indexOf(e) > -1;
});
console.log(intersection);
You can also add this method on Array prototype and call it directly on array
Array.prototype.intersection = function(arr) {
return this.filter(function(e) {
return arr.indexOf(e) > -1;
});
};
var array1 = ['apples', 'grapes', 'oranges', 'banana'],
array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];
var intersection = array1.intersection(array2);
console.log(intersection);
You can use some, like this:
let newArray = array2.filter(
(array22) => !array1.some((array11) => array11.id === array22._id));
Hi this is a porting of the function array_intersect php. Should be good for you
http://phpjs.org/functions/array_intersect/
function array_intersect(arr1) {
// discuss at: http://phpjs.org/functions/array_intersect/
// original by: Brett Zamir (http://brett-zamir.me)
// note: These only output associative arrays (would need to be
// note: all numeric and counting from zero to be numeric)
// example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
// example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
// example 1: $array3 = ['green', 'red'];
// example 1: $result = array_intersect($array1, $array2, $array3);
// returns 1: {0: 'red', a: 'green'}
var retArr = {},
argl = arguments.length,
arglm1 = argl - 1,
k1 = '',
arr = {},
i = 0,
k = '';
arr1keys: for (k1 in arr1) {
arrs: for (i = 1; i < argl; i++) {
arr = arguments[i];
for (k in arr) {
if (arr[k] === arr1[k1]) {
if (i === arglm1) {
retArr[k1] = arr1[k1];
}
// If the innermost loop always leads at least once to an equal value, continue the loop until done
continue arrs;
}
}
// If it reaches here, it wasn't found in at least one array, so try next value
continue arr1keys;
}
}
return retArr;
}
You can use
const arr1 = [1, 2, 3];
const arr2 = [2, 3];
arr1.filter(e => arr2.indexOf(e) > -1 ? false : true); // [1]
Came here some week back to find a solution to a problem like this but its a pity I couldn't get what I wanted, but now I figured it out in a more simple way. using the arrow function, .filter() method and .includes() method.
Declare an arrow function that takes in two arguments:
const filterTwoArrays = (string1, string2) => string1.filter(item => string2.includes(item));
console.log(filterTwoArrays(array1, array2)).
Here is one simple way based on your code
function array_filter(filter, result) {
var filterLen = filter.length;
var resultLen = result.length;
for (i = 0; i < resultLen; i++) {
for (j = 0; j < filterLen; j++) {
if (!contains(filter, result[i]))
result.splice(i, 1);
}
}
}
//Return boolean depending if array 'a' contains item 'obj'
function contains(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
Since you have tagged javascript here is the solution.
function f1(x, y) {
var t = y.slice(0);
var r = [];
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < y.length; j++) {
if (x[i] === y[j]) {
[].push.apply(r, t.splice(j, 1));
}
}
}
console.log(r)
y.length = 0;
[].push.apply(y, r);
}
Mark the items which are to be filtered out via delete result[index] manipulate them as needed.
JavaScript
window.onload = runs;
function runs() {
var array1 = ["apples", "grapes", "oranges"];
var array2 = ["potato", "pears", "grapes", "berries", "apples", "oranges"];
var result = filter_twoArrays(array1, array2);
function filter_twoArrays(filter, result) {
var i = 0,
j = 0;
for (i = 0; i < result.length; i++) {
var FLAG = 0;
for (j = 0; j < filter.length; j++) {
if (filter[j] == result[i]) {
FLAG = 1;
}
}
if (FLAG == 0) delete result[i];
}
return result;
}
var body = document.getElementsByTagName("body")[0];
var i = 0;
for (i = 0; i < result.length; i++) {
if (result[i] !== undefined)
body.innerHTML = body.innerHTML + result[i] + " ";
}
}
const func = array1.filter(item => array2.includes(item));

Categories

Resources