Let say we have our array like this:
let myArray = ["A", "B", "C", "D"]
What if we want to modify the order of elements in myArray based on modifier array so that, if myArray includes any element of modifier then we send that element to the end of the myArray
Like this:
let modifier = ["B"]
myArray = ["A", "C", "D", "B"] // B is sent to the end of myArray
And if we have this:
let modifier = ["A", "C"]
myArray = ["B", "D", "A", "C"] // A and C are sent to the end of the array
I have tried looping and checking each array element against another but it went complicated...
Any help would be greatly appreciated.
Very simple.
Step-1: Remove elements of modifier array from original array
myArray = myArray.filter( (el) => !modifier.includes(el) );
Step-2: Push modifier array into original array
myArray = myArray.concat(modifier)
Update
As per demands in comments by seniors :) If use case is to move multiple data:
var myArray = ["A", "A", "A", "B", "B", "B", "C", "D", "E"];
var modifier = ["A", "B"];
// get static part
staticArray = myArray.filter( (el) => !modifier.includes(el) );
// get moving part
moveableArray = myArray.filter( (el) => modifier.includes(el) );
// merge both to get final array
myArray = staticArray.concat(moveableArray);
console.log(myArray);
You could sort the array and move the items of modifier to the end of the array.
function sort(array, lastValues) {
var last = Object.fromEntries(lastValues.map((v, i) => [v, i + 1]));
return array.sort((a, b) => (last[a] || - Infinity) - (last[b] || - Infinity));
}
var array = ["A", "B", "C", "D"];
console.log(...sort(array, ["B"]));
console.log(...sort(array, ["A", "C"]));
Simply use this to get desired result
let myArray = ["A", "B", "C", "D"];
let modifier = ["A", "C"];
for(let i=0;i<modifier.length;i++){
if(myArray.includes(modifier[i])){
myArray.splice(myArray.indexOf(modifier[i]), modifier[i]);
myArray.push(modifier[i]);
}
}
console.log(myArray);
Related
Let's say I have an array
var array = ["A", "A", "A", "B", "B", "A", "C", "B", "C"];
And I want to do a check, and get true if there are 4 identical elements "A"
If I use array.includes("A"), then it looks for only one such among all and in any case returns true, but I need when there are exactly 4 such elements
Or let's say in the same array I want to find 3 elements "B" and 2 elements "C", and return true only if there are as many of them as I'm looking for, if less, then return false
How can I do this?
Take a shot like this.
const myArr = ["A", "A", "A", "B", "B", "A", "C", "B", "C"];
const findExactly = (arr, val, q) => arr.filter(x => x == val).length == q;
// logs "true" as expected :)
console.log(findExactly(myArr, 'A', 4));
So the function findExactly receives an array, a value and a number X as the quantity. Returns a boolean if the array contains the value X times. So the example above works for the example you gave on the question "And I want to do a check, and get true if there are 4 identical elements "A"".
Pulling my answer from this on stackflow.
var array = ["A", "A", "A", "B", "B", "A", "C", "B", "C"];
const counts = {};
for (const el of arr) {
counts[el] = counts[el] ? counts[el] + 1 : 1;
}
console.log(counts["A"] > 4) // 4 or more "A"s have been found
console.log(counts["B"] === 3 && counts["C"] === 3) // exactly 3 "B"s and 2 "C"s have been found
I want to get values of a map (which has values as array) and store inside a string array in typescript.
myMap = {0:['a','b','c'], 1:['d','e'], 2:['f','g']};
Expected Result arr['a','b','c','d','e','f','g']
Updated: I haven't used flat() function before. Without flat() function it gives below result.
myMap = { 0: ["a", "b", "c"], 1: ["d", "e"], 2: ["f", "g"] };
const result = Object.values(myMap);
console.log(result);
Get all values of object using Object.values and then flat the array.
myMap = { 0: ["a", "b", "c"], 1: ["d", "e"], 2: ["f", "g"] };
const result = Object.values(myMap).flat();
console.log(result);
get the key and valueArray. the iterate through the valueArray.
const myMap = {0:['a','b','c'], 1:['d','e'], 2:['f','g']};
var arr = [];
for (const [key, valueArr] of Object.entries(myMap)) {
for (var i = 0; i < valueArr.length; i++) {
arr.push(valueArr[i]);
}
}
console.log(arr);
I'm trying to filter arr2. If the element doesn't have an ID listed in arr, then I want it to be removed. How could I make this happen in javascript?
var arr= ["a", "b", "d"]
var arr2=[{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}]
result:
[{id:"a", value:1},{id:"b", value:2}]
Thanks in advance :)
You can use reduce and in the callback function check if arr includes the id of the object under iteration. If so then add the elements in the accumulator array
var arr = ["a", "b", "d"]
var arr2 = [{
id: "a",
value: 1
}, {
id: "b",
value: 2
}, {
id: "c",
value: 3
}];
const newData = arr2.reduce((acc, curr) => {
if (arr.includes(curr.id)) {
acc.push(curr)
}
return acc;
}, []);
console.log(newData)
if arr items are always strings you can do this:
var arr = ["a", "b", "d"];
var arr2 = [{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}];
let str = arr.join('')
let filtered = arr2.filter(x => str.includes(x.id));
console.log(filtered)
this should do it
var arr= ["a", "b", "d"]
var arr2=[{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}]
const filteredArray = arr2.filter(obj => {
return arr.includes(obj.id)
})
Using filter, reduce, and includes are all nearly twice as slow as simply using a loop. To walk you through it, all it does is check over every element in the second array and check to see if it's id property is in the first array, and if it is, it clones it. Also, for future reference, that title is written poorly. A much better title would be "How to filter array of objects based on a list of possible ID properties"
var arr= ["a", "b", "d"]
var arr2=[{id:"a", value:1},{id:"b", value:2}, {id:"c", value:3}]
let clone = []
for(let i = 0;i < arr2.length;i++){
for(let j = 0;j < arr.length; j++) if(arr2[i].id === arr[j]) clone.push(arr2[j])
}
console.log(clone)
I have a list with some items for example
["a", "b", "c", ..., "x", "y", "z"]
I would like to iterate it but from the end to beggining and push those items into a new variable, and stop when it has length == 3.
For that simple example I would like to have as result within my new var:
["z", "y", "x"]
I'm thinking of .reverse() my array and then iterate it with .each and push my items, but I believe there is a better way to do that with lodash, that I'm not finding.
Maybe I'm not knowing how to search.
Thanks in advance.
You can do it with the function "_.takeRightWhile" from lodash like the code below:
var arr = ["a", "b", "c", "x", "y", "z"];
var reverseArray = [];
_.takeRightWhile(arr, function(item){
reverseArray.push(item)
return reverseArray.length < 3
});
console.log(reverseArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
In plain Javascript you could use Array#slice with a negative count for getting a new array from the end and use Array#reverse for a reversed array.
var array = ["a", "b", "c", "x", "y", "z"],
result = array.slice(-3).reverse();
console.log(result);
For processing items, you could use Array#reduceRight.
var array = ["a", "b", "c", "x", "y", "z"],
result = array.slice(-3).reduceRight((r, a) => r.concat(a), []);
console.log(result);
Another solution that iterates the original array:
var arr = ["a", "b", "c", "x", "y", "z"], res=[], count=3;
if (count <= arr.length)
for (var i=0; i<count; i++) res.push(arr[arr.length-1-i]);
console.log(res);
example:
var arr = ["a", "b", "c", "d", "e", "f"];
how to check if "a", "b" and "c" are in array?
i tried indexOf() but i cant check if more than 1 strings are in array...
You are use Array.protoype.every and Array.prototype.indexOf, like this
["a", "b", "c"].every(function(currentItem) {
return arr.indexOf(currentItem) !== -1;
});
This will return true, only if all the elements in ["a", "b", "c"] are present in arr.
try like this:
var arr = ["a", "b", "c", "d", "e", "f"];
var arr1=['a','b','c'];
for(i=0;i<arr1.length;i++){
var a1 = arr.indexOf(arr1[i]);
console.log(a1);
}
or
var a = arr.indexOf("a");
console.log(a);//0
var b = arr.indexOf("b");
console.log(b);//1
var c = arr.indexOf("c");
console.log(c);//2