Comparing two arrays and push in another array wrong position element - javascript

I got two arrays, both type string :
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
and second :
var finalArray = ["0", "1", "4", "3", "5", "2"];
I would like to compare them and and if not match second with first to extract elements and push them in another array, like this :
finalArray = ["0", "1", "3"];
var toChange = ["4", "5", "2"];

You could use jQuery map method too:
var toChange = $.map(finalArray, function(v, k){
return correctAnswers[k] !== v ? v: null;
});
finalArray = $.map(finalArray, function(v, k){
return correctAnswers[k] === v ? v: null;
});
DEMO
Or using array.prototype.filter():
var toChange = finalArray.filter(function(v, k){
return correctAnswers[k] !== v;
});
finalArray = finalArray.filter(function(v, k){
return correctAnswers[k] === v;
});
filter DEMO

var toChange = [];
for (var i = finalArray.length - 1; i >= 0; i--) {
if (finalArray[i] !== correctAnswers[i]) {
toChange.push(finalArray[i]);
finalArray.splice(i, 1);
}
}
The key to this is iterating down from the length to 0, rather than up from 0 to the length as usual. This is because splice changes the indexes of all the elements after the element being removed, so normal iteration would skip an element after each splice.

This will do it:
http://jsfiddle.net/XiozZe/NkM6s/
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
var finalArray = ["0", "1", "4", "3", "5", "2"];
var correctFinal = [];
var toChange = [];
for(var i = 0; i < correctAnswers.length; i++){
if(correctAnswers[i] === finalArray[i]){
correctFinal[correctFinal.length] = finalArray[i];
}
else{
toChange[toChange.length] = finalArray[i];
}
}

First you've got to define your variables
// Define your variables
var correctAnswers = ["0", "1", "2", "3", "4", "5"];
var answers = ["0", "1", "4", "3", "5", "2"];
var finalArray = [];
var toChange = [];
Then you create a loop, which loops over the Answers array.
// comparing them could be done with a simple loop
for (var i = 0; i<answers.length; i++) {
if (correctAnswers[i] == answers[i]) { //if they're equal, push the value into the final array
finalArray.push(answers[i]);
} else { // if not, push them into the toChange array
toChange.push(answers[i]);
}
}
This will give you toChange = [0, 1, 3]
If you want toChange = [0, 1] you've got to change it to
toChange = answers.slice(0);
for (var i = 0; i<correctAnswers.length; i++) {
if (correctAnswers[i] == Answers[i]) { //if they're equal, push the value into the final array and remove the first value from the toChange array
finalArray.push(Answers[i]);
toChange.shift();
} else { // if not, break
break;
}
}
Fiddle

Related

How to change a range of array with one value Javascript?

I have an array like below let's say
var myArray = ["1", "", "", "2","3","","","8"];
And I want to fill each " " value with previous not null value
According to that expectation should be like below
var myArray = ["1", "2", "2", "2","3","8","8","8"];
Here what I tried but didn't work
var myArray = ["1", "", "", "2","3","","","8"];
function myFunction() {
let currentEl=myArray [0];
let prevIndex=0;
fruits.map((e,a)=>{
if(e!="" && myArray[a-1]==""){
currentEl=e;
let interval=arrayGenerate(a-currentIndex-1,currentEl);
fruits.splice(currentIndex-1, currentEl+1, interval);
currentIndex=a;
}
})
}
function arrayGenerate(iteration,value){
let arr=[];
for(var i=0;i<iteration;i++){
arr.push(value);
}
return arr;
}
console.log(myArray)
You could map the new values and find the missing following value.
var array = ["1", "", "", "2", "3", "", "", "8"],
result = array.map((v, i, a) => v || a.find((w, j) => j > i && w));
console.log(result);
A solution with the same array, by looping from the end and storing the last value.
var array = ["1", "", "", "2", "3", "", "", "8"],
i = array.length,
value;
while (i--) {
if (array[i]) value = array[i];
else array[i] = value;
}
console.log(array);
I have done it like this. I loop over and awlays check the next element if its falsy and not the last element.
var myArray = ["1", "", "", "2","3","","","8"];
function fillArr(arr){
for(let i = arr.length - 1; i >= 0; i--){
if(!arr[i - 1] && i != arr.length){
arr[i - 1] = arr[i];
}
}
return arr;
}
let result = fillArr(myArray);
console.log(result);
You can make use of a stack array to stack indices of null items and then unstack them whenever you encounter a non null item in myArray. (stack is not a reserved keyword so you can call it anything) :
var stack = []
for(var i = 0; i < myArray.length; i++){
if(myArray[i] === "")
stack.push(i);
else if(stack.length !== 0){
for(var j = stack.length - 1 ; j > =0; j--){
myArray[stack[j]] = myArray[i];
stack.splice(j,1);
}
}
}
It's interesting how many different ways this can be done. Just another slightly ugly way to do the same thing:
const fill = (arr, lastVal) => (
arr.reverse()
.map(el => el.length > 0 ? lastVal = el : lastVal)
.reverse()
);
console.log(fill(["1", "", "", "2","3","","","8"]));

How to make a loop with this array?

in Javascript for example I have this array:
var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
(The number of objects in the array changes constantly)
How could I get this result (a new array), and how can I separate it? for example in 3 (I probably need to make a loop for this)
var urls= ["example.com/?id0=1&id1=2&id2=3", "example.com/?id3=4&id4=5&id5=6", "example.com/?id6=7&id7=8&id8=9", "example.com/?id9=10"]
Thanks.
Use .map to add id to the ids and join the resulting array with &
var ids = ["10000000", "2000000", "1234567", "7654321", "7777777"];
var url = "example.com/?" + ids.map((id, ndx) => `id${ndx}=${id}`).join("&");
console.log(url);
EDIT
Based on the edited question, you can create function to split the array of ids into chunks and use the same code as before, map the chunks to add id and join them with &
var ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "xxx"];
const generateUrls = (ids, n = 3) => {
var i,
j,
temparray,
urls = [],
ndx = 0;
for (i = 0, j = ids.length; i < j; i += n) {
temparray =
"example.com/?" +
ids
.slice(i, i + n)
.map(id => `id${ndx++}=${id}`)
.join("&");
urls.push(temparray);
}
return urls;
};
const result = generateUrls(ids, 3);
console.log(result);

Read array values in a loop in JavaScript

I have an array in JavaScript that have defined these values:
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
And when I call a function the first time function, I need to get this:
1
2
3
Calling it again I need to get:
4
5
6
Calling it again:
7
8
9
Calling it again:
10
1
2
Calling again:
3
4
5
And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an example...so reading the array in a loop (at end, the array is read from the beginning, but always shows three values).
I try using this:
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
var arrayLength = myStringArray.length;
for (var i = 0; i < arrayLength; i++) {
if (i<(6)) {
console.log(myStringArray[i]);
}
}
But the next time I call this code, it shows from the beginning values of the array, not continue to read others value...do I need a second counter?
If you are OK with manipulating your original array as you loop through it you could splice and concat similar to below (or you could use a clone of the array if you need to persist the original array):
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
var loopByX = function(x){
var y = myStringArray.splice(0,x);
myStringArray = myStringArray.concat(y);
return y;
}
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
If you want to go bi-directional (is that what you call it?), as mentioned in the comments, you could do it as below which then gives you the ability to go backwards or forward and the flexibility to do so in an arbitrary number:
var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var loopByX = function(x) {
var len = myStringArray.length;
// Ensure x is always valid but you can add any behaviour here in that case yourself. As an example I return an empty array.
if (Math.abs(x) > len) {
return [];
}
var y = x > 0 ? myStringArray.splice(0, x) : myStringArray.splice(len + x, len);
myStringArray = x > 0 ? myStringArray.concat(y) : y.concat(myStringArray);
return y;
}
console.log(loopByX(20)); // invalid number
console.log(loopByX(-20)); // invalid number
console.log(loopByX(-3));
console.log(loopByX(-6));
console.log(loopByX(3));
console.log(loopByX(4));
You could take a function which slices three elements and if not possible, it takes the needed first values of the array as well.
function take3() {
var temp = array.slice(index, index += 3)
index %= array.length;
console.log(temp.concat(temp.length < 3 ? array.slice(0, index) : []).join(' '));
}
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
index = 0;
<button onclick="take3()">take 3</button>
With a mapping of a dynamic count.
function take(length) {
console.log(Array.from({ length }, _ => array[++index, index %= array.length]));
}
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
index = -1;
<button onclick="take(3)">take 3</button>
Your variable i is local to the for loop which means it basically resets every time the loop is started. So first make your variable i global.
var i=0;
function employeeNames(){
var empList = ["1","2","3","4","5","6","7","8","9","10"];
var output = [];
var j=0;
while(j<3)
{
output.push(empList[i])
i=(i+1)%empList.length;
j++;
}
return output;
}
console.log(employeeNames());
console.log(employeeNames());
console.log(employeeNames());
console.log(employeeNames());
console.log(employeeNames());
If you want the immutable way to achieve your circular looping
function loopArray(arr, step=3) {
let i = 0;
return function inner() {
for (let j = 0; j < step; j++) {
console.log(arr[i]);
i = (i + 1) % arr.length;
}
};
}
const func = loopArray(["1","2","3","4","5","6","7","8","9","10"], 3);
func();
func();
func();
func();
func();
The fancy solution with generator functions:
function* cycle(arr) {
let i=0;
while (true) {
yield arr[i++];
i %= arr.length;
}
}
function* chunksOf(n, iterable) {
let chunk = [];
for (const x of iterable) {
chunk.push(x)
if (chunk.length >= n) {
yield chunk;
chunk = [];
}
}
if (chunk.length > 0)
yield chunk;
}
function toFunction(iterator) {
return () => iterator.next().value;
}
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
const f = toFunction(chunksOf(3, cycle(myStringArray)));
console.log(f());
console.log(f());
console.log(f());
// …
#Igor Petev, JavaScript's closures are a nice concept that you can use to solve your problem.
Please read JavaScript's Closures - w3schools article. It's really nice and excellent.
I have used the concept of closures to solve this problem. Please leave a comment if you don't understand my code or anything else related to this problem.
Please have a look at the below code.
var get3items = (function () {
var index = 0;
var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var len = myStringArray.length
return function () {
for(var count = 0; count < 3; count += 1)
{
console.log(myStringArray[index]);
if(index == (len - 1))
{
index = 0;
}
else {
index += 1;
}
}
}
})();
get3items (); // First call
console.log()
get3items (); // Second call
console.log()
get3items (); // Third call
console.log()
get3items (); // Fourth call
console.log()
get3items (); // Fifth call
/*
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
*/
How about using a generator:
function* get3() {
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
var index = 0;
while (true) {
yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length])
index = (index + 3) % myStringArray.length;
}
}
Calling this function returns an object which you can call .next() on, to get the next set of 3:
var getter = get3();
console.log(getter.next().value); // ["1","2","3"]
console.log(getter.next().value); // ["4","5","6"]
console.log(getter.next().value); // ["7","8","9"]
// etc.
function* employeeNames(){
var empList = ["1","2","3","4","5","6","7","8","9","10"];
for(var i =0; i<=empList.length; i++){
yield empList[i];
}
}
var emp;
emp = employeeNames();
It uses a generator function...

Transforming array with numbers and operators

I manage to have this arraylist :
["1","2","+","2","1","2"]
But I would like to sort it in order to have
["12","+","212"]
But I can't figure out how to this.
UPDATE :
let al = ["1","2","+","2","1","2"];
for(let i=0;i.length;i++) {
if(al[i] != "+" && al[i+1]) {
al[i] += al[i+1];
}
}
I think I could use a while loop
Combine join and split by regex:
var a = ["1","2","+","2","1","2"];
a = a.join('').split(/([x^+-])/);
console.log(a);
You could join and split by word boundary position, without mention the operators.
var array = ["1", "2", "+", "2", "1", "2"],
result = array.join('').split(/\b/);
console.log(result);
This is the easiest way. Just write a reducer to append tokens to a stack.
const OPERATORS = /[+\-\*\/]/;
function toExpression(tokens) {
return tokens.reduce((result, token) => {
if (OPERATORS.test(token)) {
result.push(token, '');
} else {
result[result.length - 1] += token;
}
return result;
}, ['']);
}
let arr1 = ["1", "2", "+", "2", "1", "2"];
let arr2 = toExpression(arr1);
console.log(JSON.stringify(arr2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Just go over the array and join everytging except the + :
const array = ["1", "2", "+", "2", "1", "2"]
const result = [];
let curr = "";
for (const el of array) {
if (el == "+") {
result.push(curr, el);
curr = "";
} else {
curr += el;
}
}
result.push(curr);
console.log(result)

browse a table and share it on 2 tables in javascript

I have a table that follows a defined sequence that Repite : [ col , name , value1, value2 , value 3, col, name value1, value2, value3 ..col , name , value1, value2 , value 3 ]
code:
var data =["DN","Atac","1","2","3","PDA","Atac","5","6","7","EPDA","Atac","8","9","11","DN Potentielle","Atac","14","4","8"] ;
I try to split the data table col , name , values:
Code result :
var column = ["DN","PDA","EPDA","DN Potentielle"];
var name ="Atac";
var values =[ "1","2","3","5","6","7","8","9","11","14","4","8"];
how has the simplest method without a lot of code to do it
If you're sure that your data is consistent and can rely on the structure you wrote, the simplest thing would be:
var column = [];
var name = [];
var values = [];
for (var i = 0; i < data.length; i = i+5) {
column.push(data[i]);
name.push(data[i+1]);
values.push(data[i+2]);
values.push(data[i+3]);
values.push(data[i+4]);
};
name = name.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
console.log(column); //["DN","PDA","EPDA","DN Potentielle"]
console.log(name); //["Atac"]
console.log(values); //["1", "2", "3", "5", "6", "7", "8", "9", "11", "14", "4", "8"]
Fiddle
Set up an object to hold the values:
var obj = { column: [], name: null, values: [] };
Then cycle over the array in groups of 5, adding the various elements to the object:
for (var i = 0, l = data.length; i < l; i+=5) {
obj.column.push(data[i]);
obj.name = data[i + 1];
// push.apply is a neat way of concatenation that doesn't
// require the creation of a new variable
obj.values.push.apply(obj.values, data.slice(i + 2, i + 5));
}
DEMO
I try to figure out what you want, and the best way is to retrieve the number value and string value without spliting it.
var data =["DN","Atac","1","2","3","PDA","Atac","5","6","7","EPDA","Atac","8","9","11","DN Potentielle","Atac","14","4","8"] ;
var columns = [];
var values = [];
$.each(data, function(k, v) {
var parsedValue = parseInt(data[k]);
if ( ! isNaN(parsedValue) ) {
values.push(parsedValue);
} else {
columns.push(v);
}
});
console.log(columns);
console.log(values);
Demo: http://jsfiddle.net/bzryqs84/1/

Categories

Resources