Mapping Arrays in JavaScript

Imagine this situation;

var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];

When passing certain index's values as parameters, the array needs to be split up.

For example:

If Array Index : 0,2

Desired outcome:

availArr = ['b', 'd'];
selectedArr = ['a', 'c'];

Is there a built-in method to accomplish this?

Answer №1

Quite simple using the power of Array.reduce

var myArr = ['x', 'y', 'z', 'w'];
var positions = [1,3];

var output = myArr.reduce(function(previous, current, index){
  if(positions.indexOf(index) > -1)
    previous.chosenArr.push(current);
  else
    previous.remainingArr.push(current);
  return previous;
}, {remainingArr: [], chosenArr:[]});

console.log('remainingArr',output.remainingArr);
console.log('chosenArr',output.chosenArr);

This solution hinges on the concept that reduce accepts a callback function with 3 arguments - as seen in the example provided

  • previous the initial object passed in
  • current the element currently being processed
  • index the position of the current element

By utilizing this information and the indexOf method, we can effectively differentiate between arrays for storage.

Answer №2

If you want to manipulate arrays in JavaScript, you can utilize the Array#reduceRight method and cycle through the indices array.

var initialArray = ['x', 'y', 'z', 'w'],
    newArray = initialArray.slice(),
    selectedItems = [],
    indexList = [1, 3];

indexList.reduceRight(function (_, index) {
    selectedItems.unshift(newArray.splice(index, 1)[0]);
}, 0);

console.log(newArray);
console.log(selectedItems);

Answer №3

var newArray = ['x', 'y', 'z', 'w'];
var availableItems = [];
var selectedItems = [];

function rearrangeArray(indices) {
  availableItems = newArray; 
  indices.forEach(function(index) {
    let value = availableItems.splice(index, 1)[0];
    selectedItems.push(value);
  })
}

rearrangeArray([0, 2]);

console.log(availableItems);
console.log(selectedItems);

Answer №4

To make use of Array methods such as forEach and includes

var data = ['x', 'y', 'z', 'w'];
var indices = [1, 3];
var options = [];
var choices = [];

data.forEach(function (item, index) {
  if (indices.includes(index)) {
    choices.push(item);
  } else {
    options.push(item);
  }
});

document.write(JSON.stringify({
  data: data,
  options: options,
  choices: choices
}));

Answer №5

When working in JS, Array.prototype.reduceRight() serves as the perfect functor for iterating through an array and modifying it by eliminating certain items. My preferred approach to this task would be:

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);

Answer №6

To achieve this, you can utilize the array.splice method along with array.concat.

var defaultArr = ['a', 'b', 'c', 'd'];
var availArr = [];
var selectedArr = [];

function manipulateIndexes(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)
}

manipulateIndexes([0,2])

Answer №7

If you only use the Array.filter method:

var array = ['a', 'b', 'c', 'd'];
var indexes = [0, 2]
array.filter(function(el, i) { 
    return indexes.indexOf(i) !== -1 
});

// ["a", "c"]

By using array as the collection of your elements like objects or strings and indexes as the array containing the specific indexes you want to keep, you can easily filter out unwanted elements from the array based on their index.

Answer №8

You can easily retrieve all selected entries by using a single line of code with the Array.map:

const defaultArr = ['x', 'y', 'z', 'w']
const index = [1,3]
const selectedEntries = index.map(i => defaultArr[i]) //=> ['y', 'w']

To get the array of remaining entries, you can use Lodash's difference method:

const availableEntries = _.difference(defaultArr, selectedEntries) //=> ['x', 'z']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in the HTML DOCTYPE declaration affecting JavaScript files

My login page is displaying 5 errors, specifically a syntax error SyntaxError: syntax error <!DOCTYPE html> on 5 JavaScript files. After investigating, I discovered that these files are located in a non-public directory. Is there a way to exclude th ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Using AngularJS to showcase information received from socket.io

I'm having an issue with displaying data on a graph using AngularJS after receiving it from socket.io. Even though I can see that the data is being retrieved correctly from the server, when I try to display it on the graph, I only get a message saying ...

Why is it that my jquery code seems to be struggling with calculating the count accurately?

I'm currently working on restricting keyword input on my website. My goal is to automatically add a 'span' tag to any keyword entered by a user, as shown in the example html code below. Although I can limit the number of words, the count i ...

Why won't my jQuery datepicker show up?

I am encountering these issues with IE7: Line 22: object does not support this property or method line 142: invalid argument I am attempting to implement a datepicker on a textbox: <script> jQuery(function($) { $("#<%= re ...

Tips for displaying the overlay in a jQuery UI modal dialog

The demonstration shows that the overlay is displayed correctly and all elements below it are disabled: <div class="ui-widget-overlay" style="width: 1920px; height: 650px; z-index: 1001;"></div> However, on my webpage, I am still able to inte ...

Utilizing JQuery's printThis Plugin in Combination with the Style Attribute

I am currently working on a JavaScript app and I am trying to implement a button that will allow users to print a specific div. To achieve this, I am utilizing a jQuery plugin called printThis (github link) as well as attempting to use window.print(). $(" ...

In a scenario where multiple fields need to be incremented, one can accomplish this by incrementing one field every time while also increasing the other field only if it exceeds a

When trying to decrement class_number, everything works fine. However, the issue lies with number_of_classes not being decremented due to the usage of the $gt operator. posts.update({ 'title':doc.title, 'author':doc.author, 'class ...

The jQuery code causes IE6 to crash

The code snippet above is triggering a crash in IE6 every time it runs. The page keeps refreshing and eventually crashes after a minute: $(window).bind("load resize", function () { var hnf = $('#header').height() + $('#footer').hei ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

Creating a test suite with Jasmine for an Angular ui-grid component compiled without using $scope

I have encountered an issue while using $compile to compile a ui-grid for Jasmine testing. Initially, everything worked smoothly when I passed $scope as a parameter to the controller. However, I am now transitioning to using vm, which has resulted in $comp ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

Error: The function $.ajax(...).done(...).fail(...).complete does not exist

Out of nowhere, I started encountering the error message below: TypeError: $.ajax(...).done(...).fail(...).complete is not a function Below is my code snippet: this.sendRequest = function (type, extension, data, successCallback, successMsg, failMsg, ...

When retrieving values from an array using an index, it may result in

I am attempting to access a specific index of an array within a JSON object. For instance, here is the JSON object retrieved from MongoDB: { _id: 55b65199c92d15d80fd94803, site: 'test.com', company: 'test', __v: 0, votes: [ ...

Transform the elements in an ArrayList into a single string separated by commas

Greetings fellow developers, After successfully deserializing an ArrayList from a text file in my application, I now have a list of Strings. In order to enhance the design, I aim to combine the contents of this ArrayList into a single organized string wit ...

The transmission of information through Ajax is encountering a problem as the data is not properly

Having some trouble using Ajax to send form data and echoing it on the PHP page. Since I'm new to Ajax, I might have made a mistake somewhere in my code. Below is what I currently have: $(function () { $('form').on('submit&apos ...

Utilizing Typescript generics in scenarios with arguments that may be either a value or a callback function

Here's the issue: I need to pass T, which could be a string, number, boolean, object, array, or a function. The problem is I can't figure out how to handle ab("hello") in this scenario and return T as a value. function a<T>(ab: T | ((v: T) ...

Retrieve all default and user-defined fields associated with contacts in the CRM 2011 system

In CRM 2011, the contact entities come with a variety of default fields, and I have also included some custom fields. My goal is to retrieve all field names in a JavaScript list. When creating an email template in CRM, you can select fields from a dialog. ...

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...