I have two arrays which contains equal length:
var a = [a, b,c,d,e];
var b = [1,2,3,4,5];
I have another variable 'C' which contains one the value of array a
var c = "d";
How do I remove '4' in another array 'b' based on the value of var C.
Final values required:
finala = [a,b,c,e];
finalb = [1,2,3,5];
removeda = d;
removedb = 4;
You could use Array#indexOf for the index and use Array#splice for both arrays.
var a = ['a', 'b', 'c', 'd', 'e'],
b = [1, 2, 3, 4, 5],
c = 'd',
index = a.indexOf(c),
removeda = a.splice(index, 1)[0],
removedb = b.splice(index, 1)[0];
console.log(a);
console.log(b);
console.log(removeda);
console.log(removedb);
.as-console-wrapper { max-height: 100% !important; top: 0; }
There you go.
Removing elements from both arrays, and storing what elements you removed:
var a = ['a', 'b','c','d','e'],
b = [1,2,3,4,5],
c = "d",
index = a.indexOf(c);
var removedA = a.splice(index, 1)[0];
var removedB = b.splice(index, 1)[0];
console.log(a);
console.log(removedA)
console.log(b);
console.log(removedB)
Use Array#splice and Array#indexOf methods.
var a = ['a', 'b', 'c', 'd', 'e'];
var b = [1, 2, 3, 4, 5];
var c = "d";
// get index of eleemnt in array `a`
var i = a.indexOf(c);
// remove element and store them in variable
var removeda = a.splice(i, 1)[0],
removedb = b.splice(i, 1)[0];
console.log(a, b, removeda, removedb)
This should do the work
var index = a.indexOf(c)
var removeda = a.splice(index, 1)[0];
var removedb = b.splice(index, 1)[0];
Related
I have an array like [a, b, c, d] and I want to split it into 2 arrays like [a, b] and [c, d] and then merge it to have final result like [[a, b],[c, d]]. Is it possible to do without for loop?
You can use slice and push method like this
var arr = ['a', 'b', 'c', 'd'];
let index = 2;
let result = [];
result.push(arr.slice(0, index));
result.push(arr.slice(index))
console.log(result);
let arr = [0, 1, 9, 10, 8];
let arr2 = arr.slice(1,3);
let resultArr = [];
if(arr2[1] > 1){
resultArr.push(99);
}
else{
resultArr.push(100);
}
console.log(resultArr)
You might like something like this:
a = 8;
b = { some: 'say'};
c = 'life';
d = true;
let o = {
'a': [a, b, c, d],
'a1': [],
'a2': []
}
nSwitchBefore = 2;
o.a.forEach(function(item, i) {
i < nSwitchBefore ? this.a1.push(item) : this.a2.push(item) ;
}.bind(o));
console.log(o);
Within the function block there is room for extra handling your array items. Like filtering or special treatment of certain types, using all conditions you want.
yes without loop you can do this But you should know at what index you have to split the array.
var arr = ['a', 'b', 'c', 'd'];
var indexToSplit = arr.indexOf('c');
var first = arr.slice(0, indexToSplit);
var second = arr.slice(indexToSplit + 1);
var final = [first, second]
console.log(final);
I found another solution for this issue, without writing loops
Lodash Chunk does this logic
_.chunk(['a', 'b', 'c', 'd'], 2);
// => [['a', 'b'], ['c', 'd']]
https://lodash.com/docs/
I have 2 arrays. I am trying to return the similar values between the 2 but in the order of the second. For example, take a look at the two arrays:
array1 = ['a', 'b', 'c']
array2 = ['b', 'c', 'a', 'd']
What I would like to return is this:
sim = ['b', 'c', 'a']
Here is a link to what I am trying to accomplish. Currently the script is faulty and not catching the corner case.
You could use a Set for array1 use Array#filter array2 by checking the set.
var array1 = ['a', 'b', 'c'],
array2 = ['b', 'c', 'a', 'd'],
theSet = new Set(array1),
result = array2.filter(v => theSet.has(v));
console.log(result);
Some annotations to your code:
function arr_sim (a1, a2) {
var //a = {}, // take an object as hash table, better
a = Object.create(null), // a really empty object without prototypes
sim = [],
i; // use single declaration at top
for (i = 0; i < a1.length; i++) { // iterate all item of array 1
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
sim.push(a2[i]); // just push the value
}
}
return sim;
}
console.log(arr_sim(['a', 'b', 'c'], ['b', 'c', 'a', 'd']));
You can iterate array2 with a filter, and check if the value is contained in array1:
let array1 = ['a', 'b', 'c'];
let array2 = ['b', 'c', 'a', 'd'];
let sim = array2.filter((entry) => {
return array1.includes(entry);
});
console.log(sim);
I think this is what you are looking for?
function arr_sim (a1, a2) {
a1 = Array.isArray(a1)?a1:typeof a1 == "string"?a1.split(""):false;
a2 = Array.isArray(a2)?a1:typeof a2 == "string"?a2.split(""):false;
if(!a1 || !a2){
alert("Not valid values");
return;
}
var filterArray = a1.filter(function(val){
return a2.indexOf(val) !== -1;
})
return filterArray;
}
console.log(arr_sim(['a', 'b'], ['b', 'a', 'c', 'd']));
console.log(arr_sim("abcd", "abcde"));
console.log(arr_sim("cxz", "zcx"));
Try this
const arr_sim = (a1, a2) => a2.filter(a => a1.includes(a))
console.log(arr_sim(['a', 'b', 'c'], ['b', 'c', 'a', 'd']));
try this example here similar-values betwe
en two arrays
var a1 = ['a' ,'b'];
var a2 = ['a' ,'b' ,'c'];
var result = arr_sim(a1,a2);// call method arr_sim
console.log(result);
function arr_sim (a1, a2) {
var similar = [];
for( var i = 0 ; i <a1.length ; i++ ){ // loop a1 array
for( var j = 0 ; j <a2.length ; j++ ){ // loop a2 array
if( a1[i] == a2[j] ){ // check if is similar
similar.push(a1[i]); // add to similar array
break; // break second loop find that is similar
} // end if
} // end second lopp
} // end first loop
return similar; // return result
} // end function
I have an array [a, b, c]. I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0].
I guess it would be something like this, but I can't make it works.
for (let i = 0; i < array.length; i++) {
newArray = [
...array.splice(0, i),
0,
...array.splice(i, array.length),
];
}
Thank you for helping me!
For getting a new array, you could concat the part an add a zero element for each element.
var array = ['a', 'b', 'c'],
result = array.reduce((r, a) => r.concat(a, 0), [0]);
console.log(result);
Using the same array
var array = ['a', 'b', 'c'],
i = 0;
while (i <= array.length) {
array.splice(i, 0, 0);
i += 2;
}
console.log(array);
A bit shorter with iterating from the end.
var array = ['a', 'b', 'c'],
i = array.length;
do {
array.splice(i, 0, 0);
} while (i--)
console.log(array);
Another way if you want to exclude the start and end of array is :
var arr = ['a', 'b', 'c']
var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b))
console.log(newArr)
You can use map() with ES6 spread syntax and concat()
var arr = ['a', 'b', 'c']
var newArr = [0].concat(...arr.map(e => [e, 0]))
console.log(newArr)
Another ES6+ version using flatmap (if creation of a new array instead is ok):
['a', 'b', 'c', 'd']
.flatMap((e, index) => index ? [e, 0] : [0, e, 0])
Another way:
var a = ['a', 'b', 'c'],
b;
b = a.reduce((arr, b) => [...arr, b, 0], []);
console.log(b);
You could use .reduce():
function intersperse(arr, val) {
return arr.reduce((acc, next) => {
acc.push(next);
acc.push(val);
return acc;
}, [val]);
}
console.log(intersperse(['a', 'b', 'c'], 0));
Or to accomplish this by modifying the original array:
function intersperse(arr, val) {
for (let i = 0; i <= arr.length; i += 2) {
arr.splice(i, 0, val);
}
return arr;
}
console.log(intersperse(['a', 'b', 'c'], 0));
You can try with the below code. It will add 0 in middle of each two element of the array
console.log(['a', 'b', 'c'].reduce((r, a) => r.concat(a,0), [0]).slice(1, -1))
You just need to loop over the array elements and add the new element in each iteration, and if you reach the last iteration add the new element after the last item.
This is how should be your code:
var arr = ['a', 'b', 'c'];
var results = [];
arr.forEach(function(el, index) {
results.push(addition);
results.push(el);
if (index === arr.length - 1)
results.push(addition);
});
Demo:
This is a Demo snippet:
var arr = ['a', 'b', 'c'];
var results = [];
var addition = 0;
arr.forEach(function(el, index) {
results.push(addition);
results.push(el);
if(index === arr.length -1)
results.push(addition);
});
console.log(results);
If you want to insert elements only after existing ones:
console.log(["a", "b", "c"].map(i => [i, 0]).flat())
You could do
let arr = ['a', 'b', 'c'];
arr = arr.reduce((a, b) => {
a.push(0);
a.push(b);
return a;
}, []);
arr.push(0);
console.log(arr);
function insert(arr, elm) {
var newArr = [];
for(var i = 0; i < arr.length; i++) { // for each element in the array arr
newArr.push(elm); // add the new element to newArr
newArr.push(arr[i]); // add the current element from arr
}
newArr.push(elm); // finally add the new element to the end of newArr
return newArr;
}
console.log(insert(["a", "b", "c"], 0));
It could be done with strings by splitting and joining.
var arr = ['a', 'b', 'c'];
var newArray = ("0," + arr.toString().split(",").join(",0,")).split(",");
console.log(newArray);
This looks like the intersperse algorithm but does some addition to the head and tail as well. So i call it extrasperse.
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
extrasperse = (x,a) => a.reduce((p,c,i) => (p[2*i+1] = c, p), Array(2*a.length+1).fill(x));
console.log(JSON.stringify(extrasperse("X",arr)));
let arr = ['a', 'b', 'c'];
function insert(items, separator) {
const result = items.reduce(
(res, el) => [...res, el, separator], [separator]);
return result;
}
console.log(insert(arr, '0'));
all of the above methods in very long strings made my android computer run on React Native go out of memory.
I got it to work with this
let arr = ['a', 'b', 'c'];
let tmpArr = [];
for (const item in arr) {
tmpArr.push(item);
tmpArr.push(0);
}
console.log(tmpArr);
Another way is to use some functional methods like zip and flat. Check out lodash.
const array = ['a', 'b', 'c']
const zeros = Array(array.length + 1).fill(0)
const result = _.zip(zeros, array).flat().filter(x => x !== undefined)
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Straight forward way of inserting only between:
const arr = ['a', 'b', 'c'];
arr.map((v, i) => !i || i === arr.length - 1 ? [v] : [0, v]).flat()
I think this is correct, ie, just adds the element between the elements of the array, and should be pretty efficient:
const intersperse = ([first, ...tail]: any[], element: any) => (
(first === undefined) ? [] : [first].concat(...tail.map((e) => [element, e]))
);
console.log(intersperse([], 0));
console.log(intersperse([1], 0));
console.log(intersperse([1, 2, 3], 0));
Thanks for your question and thanks to all contributors, for their answers.
This would be my approach
const arr = ["a", "b", "c"];
let toAdd = 0;
for (let i = 0; i <= arr.length; i += 2) {
arr.splice(i, 0, toAdd);
}
console.log(arr);
or
const arr = ["a", "b", "c"];
let toAdd = 0;
const newArr = [];
newArr.unshift(toAdd);
for (let i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
newArr.push(toAdd);
}
console.log(newArr);
Cheers
Nav
:) I need to return a new object whose properties are those in the given object and whose keys are present in the given array.
code attempt:
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
function select(arr, obj) {
var result = {};
var array = [];
for (var key in obj){
array.push(key);
}
var num = arr.length + obj.length;
for (var i = 0; i < num; i++) {
for(var j = 0; j < num; j++) {
if (arr[i] === array[j]) {
result.array[i] = obj.arr[i];
}
}
}
return result;
}
(incorrect) result:
{}
desired result:
// --> { a: 1, c: 3 }
Any advice? Thank you! :)
Longer, but more readable version:
var arr = ['a', 'c', 'e'],
obj = {a:1,b:2,c:3,d:4},
hash = {};
arr.forEach(function(v){ //iterate over each element from arr
Object.keys(obj).some(function(c){ //check if any key from obj is equal to iterated element from arr
if (v == c) {
hash[v] = obj[c]; //if it is equal, make a new key inside hash obj and assign it's value from obj to it
}
});
});
console.log(hash);
Short version:
var arr = ['a', 'c', 'e'],
obj = {a:1,b:2,c:3,d:4},
hash = {};
arr.forEach(v => Object.keys(obj).some(c => v == c ? hash[v] = obj[c] : null));
console.log(hash);
You could iterate the given keys, test if it is a key in the object and assign the value to the same key in the result object.
function select(arr, obj) {
var result = {};
arr.forEach(function (k) {
if (k in obj) {
result[k] = obj[k];
}
});
return result;
}
var arr = ['a', 'c', 'e'],
obj = { a: 1, b: 2, c: 3, d: 4 };
console.log(select(arr, obj));
Consider the following scenario;
var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];
If I am passing array some index's value in param's, I need to split up my array's
Example:
If Array Index : 0,2
Expected result:
availArr = ['b', 'd'];
selectedArr = ['a', 'c'];
Is there any default method to achieve this?
Failrly easy with Array.reduce
var defaultArr = ['a', 'b', 'c', 'd'];
var indexes = [0,2];
var result = defaultArr.reduce(function(p, c, i){
if(indexes.indexOf(i)>-1)
p.selectedArr.push(c);
else
p.availArr.push(c);
return p;
}, {availArr: [], selectedArr:[]});;
console.log('availArr',result.availArr);
console.log('selectedArr',result.selectedArr);
This works because reduce takes a callback argument which is passed 3 arguments - in my example above
p the seed object passed in
c the current array element
i the index of the current element
And uses that information along with indexOf to determine which result array to push to.
You could use Array#reduceRight and iterate the indices array.
var defaultArr = ['a', 'b', 'c', 'd'],
availArr = defaultArr.slice(),
selectedArr = [],
indices = [0, 2];
indices.reduceRight(function (_, a) {
selectedArr.unshift(availArr.splice(a, 1)[0]);
}, 0);
console.log(availArr);
console.log(selectedArr);
var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];
function splitArray(indexes) {
availArr = defaultArr;
indexes.forEach(function(idx) {
let item = availArr.splice(idx, 1)[0];
selectedArr.push(item);
})
}
splitArray([0, 2]);
console.log(availArr);
console.log(selectedArr);
You can use Array methods like forEach and includes
var given = ['a', 'b', 'c', 'd'];
var indexes = [0, 2];
var available = [];
var selected = [];
given.forEach(function (v, i) {
if (indexes.includes(i)) {
selected.push(v);
} else {
available.push(v);
}
});
document.write(JSON.stringify({
given: given,
available: available,
selected: selected
}));
In JS Array.prototype.reduceRight() is the ideal functor to iterate over an array and to morph it by removing items. Accordingly i would approach this job as follows;
var defaultArr = ['a', 'b', 'c', 'd'],
indices = [0, 2];
result = defaultArr.reduceRight((p,c,i,a) => indices.includes(i) ? p.concat(a.splice(i,1)) : p ,[]);
console.log(defaultArr,result);
You can use array.splice + array.concat to achieve this
var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];
function parseIndexes(indexArr){
var deleteCount = 0;
availArr = defaultArr.map(x=>x);
indexArr.forEach(function(i){
selectedArr = selectedArr.concat(availArr.splice(i-deleteCount,1))
deleteCount++;
});
console.log(availArr, selectedArr)
}
parseIndexes([0,2])
With only Array.filter
var array = ['a', 'b', 'c', 'd'];
var indexes = [0, 2]
array.filter(function(el, i) {
return indexes.indexOf(i) !== -1
});
// ["a", "c"]
With array the array of your elements, objects, strings... and indexes the array containing all the indexes of the elements you want to keep, you just remove from the arrayarray all the elements whose id isn't in theindexes array.
The array of all selected entries can be obtained in one line via the Array.map:
var defaultArr = ['a', 'b', 'c', 'd']
var index = [0,2]
var selectedArr = index.map(i => defaultArr[i]) //=> ['a', 'c']
Then the array of the remaining entries can be retrieved e.g. with the Ramda's difference operator:
var availArr = R.difference(defaultArr, selectedArr) //=> ['b', 'd']